<?php

namespace app\api\controller;

use app\api\model\Labels;
use app\api\model\Privatechat as Chat;
use app\api\model\PrivatechatDefault;
use app\api\model\Socket;
use app\api\model\VolleyDesc as Balance;
use app\api\model\ConfigSystem as Config;
use app\api\model\Task;
use app\api\model\User;
use app\api\model\ChatLists;
use app\api\model\Blacklist;
use GatewayClient\Gateway;
use think\Db;
use Think\Log;
use think\Request;
use think\Cache;
use think\response\Json;
use app\api\model\PrivatechatDeleTask;
use app\api\model\PrivatechatGreet;
use app\service\AliOss;
use app\service\TrtcService;
use app\service\UserIntimate as UserIntimateService;
use app\api\model\ShenheTask;

class Privatechat extends Common
{
    
    public  function  recharge_amount(){
        $id = input('amount_user_id', 0);
        $money = Db::name('topup')->where(['fk_userid'=>$id,'state'=>1])->sum('price');
        if ($money >0){
            $money = floor($money*100)/100;
        }else{
            $money = 0;
        }
        $data = [
            'amount'=>$money,
        ];
        return $this->pass($data);
    }
    
        public function callback()
    {
        $post_data = $_POST;
        $get_data = $_GET;
        
        Log::write('这是post数据:'.json_encode($post_data));
        Log::write('这是get数据:'.json_encode($get_data));
        Log::write('数据到这里结束了');

    }
    
        public function test_push()
    {

$msg = '测试推送信息'.rand(100,999);
    $push = new Push($this->request);
    $result  = $push->send(20381353, 2, '那蓝之恋'.rand(200,300), $msg);

echo $msg;
    print_r($result);
    die();
}
    // 个人聊天常用语
    public function commonWords($user_id = 0)
    {
        //$types = $this->member['sex'] == '男' ? 1 : 2;

        // if(!$user_id){
        //     return $this->pass([]);
        // }

    //   if($user_id != 6382){
    //         return $this->pass([]);
    //     }
        $user_id = intval($user_id);
        $where = [
            'user_id' => $user_id,
            'shenhe_state'=>1
        ];
        $channel = $this->params['channel'] ?? 2;
        $all = $this->params['all'] ?? 0;
        if ($all) {
            $channel = 0;
            $limit = 50;
        } else {
            $where['channel'] = $channel;
            $limit = 20;
        }

        $data = PrivatechatDefault::where($where)->field('id, content, channel, image')->order('id desc')->limit($limit)->cache("word&$channel&$user_id", 600)->select();

        return $this->pass($data);
    }

    // 添加常用语
    public function addCommonWords()
    {
        $content = strip_tags($this->params['content']);


        $contain = Db::name('filter_word')->where(['state' => 1])->column('name');
        foreach ($contain as $v) {
            if (stripos($content, $v) !== false) {
                exit(json_encode(['code' => 400, 'msg' => '内容含有敏感词"' . $v . '",请重新编辑']));
            }
        }

        $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'chat']]])->column('title, content');
        $kefu = intval($config['id']);
        $shenhe_state = 0;
        if ($this->member['id'] == $kefu) {
            $shenhe_state = 1;
        }

        $channel = $this->params['channel'] ?? 2;

        if (isset($this->params['id']) && $this->params['id']) {
            PrivatechatDefault::update(['id' => $this->params['id'], 'user_id' => $this->member['id'], 'content' => $content]);
        } else {
            $types = $this->member['sex'] == '男' ? 1 : 2;

            PrivatechatDefault::create([
                'user_id' => $this->member['id'],
                'types' => $types,
                'channel' => $channel,
                'content' => $content,
                'shenhe_state' => $shenhe_state,
            ]);
        }

        Cache::rm("word&0&". $this->member['id']);
        Cache::rm("word&$channel&". $this->member['id']);

        return $this->return['common.success.submit'];
    }

    public function delCommonWords()
    {
        $word = PrivatechatDefault::get(['id' => $this->params['word_id'], 'user_id' => $this->params['user_id']]);

        if ($word) {
            $channel = $word['channel'];
            Cache::rm("word&$channel&". $this->params['user_id']);
            PrivatechatDefault::destroy($word['id']);
        } else {
            return $this->return['chat.error.wordNotExist'];
        }

        return $this->return['common.success.submit'];
    }

    // 心动、速配
    public function greet($id = '', $speed = 0, $content = '')
    {
        // return $this->pass(' ');
        if(cache('greet' . $this->member['id'])){
            return $this->miss('点击太过频繁，请稍后再试');
        }
        
        $is_hello = cache('greet'.$this->member['id'].'-to-' . $id);
        if ($is_hello){
            return $this->miss('两小时内不能再撩哦，直接私聊TA吧');
        }
        // if ($speed) {
            // $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'chat']]])->column('title, content');
            // $kefu = intval($config['id']);

            $request = request();

            if ($speed) {
                return $this->miss('该功能暂不开放');
                $sex = $this->member['sex'] == '男' ? '女' : '男';
                $where = ['id' => ['neq', $kefu], 'sex' => $sex, 'city' => ['like', '%' . $this->member['city'] . '%']];

                if ($this->member['sex'] == '男') {
                    $where['sex'] = '女';
                    $where['is_identity_authentication'] = 2;
                    $sql_where = ' and is_identity_authentication = 2';
                } else {
                    $where['sex'] = '男';
                    $sql_where = '';
                }

                $ids = Db::name('user')->where($where)->orderRaw('rand()')->limit($speed)->column('id');

                $num = $speed - count($ids);
                if ($num > 0) {
                    $idsArr = $ids;
                    $idsArr[] = $kefu;
                    $idsStr = implode(',', $idsArr);

                    $sql = "select *, case 
                                when xuni_discount = '0.0' then 
                                    ROUND(
                                        6378.138 * 2 * ASIN(
                                            SQRT(
                                                POW(
                                                    SIN(
                                                        (" . $this->member['latitude'] . " * PI() / 180 - latitude * PI() / 180) / 2
                                                    ), 2
                                                ) + COS (" . $this->member['latitude'] . " * PI() / 180) * COS(latitude * PI() / 180) * POW(
                                                    SIN(
                                                        (" . $this->member['longitude'] . " * PI() / 180 - longitude * PI() / 180) / 2
                                                    ), 2
                                                )
                                            )
                                        ) * 1000
                                    ) 
                                else 
                                    xuni_discount END distance from user where id not in ($idsStr) and sex = '$sex'" . $sql_where . " ORDER BY distance limit $num";

                    $role = Db::query($sql);

                    foreach ($role as $item) {
                        $ids[] = $item['id'];
                    }
                }
            } else {
                $ids = [$id];

                // $fields = $this->member['id'] < $id ? 'couple_a' : 'couple_b';
                // $intimate = Db::name('user_intimate')->where([$fields=>$this->member['id'].','.$id, 'unshow'=>0])->value('intimate');
                // if($intimate && $intimate>0){
                //     exit(json_encode(['code'=>400, 'msg'=>'你们曾经交流过了，不能再向对方打招呼']));
                // }
            }
            // $touser = Db::name('user')->where(['id'=>$id])->field('id,yqr,yqm')->find();

            if ($this->member['sex'] == '女') {
                
                
                if ($this->member['realname_auth'] != 2) {
                    return $this->miss('未实名认证');
                }

                if (strtotime($this->member['register_datetime']) >=1749787200 &&  $this->member['is_identity_authentication'] != 2) {
                    return $this->miss('未真人认证');
                }
                
                // if ($this->member['realname_auth'] == 2) {
                    
                // } else if(strtotime('2023-06-01') > strtotime($this->member['register_datetime'])){
                //     return $this->miss('未实名认证');
                // } else if ($this->member['is_identity_authentication'] != 2) {
                //     return $this->miss('未真人认证');
                // } else {
                //     $hasAuthIdCard = Db::name('user_certification')->where(['types'=>1, 'user_id'=>$this->member['id']])->find();
                //     if (!$hasAuthIdCard || $hasAuthIdCard['status'] == -1) {
                //         return $this->miss('未实名认证');
                //     }
                // }
            }
            // $touserConfig = Db::name('config_personal')->where(['user_id' => ['in', $ids]])->column('user_id, chat_price');

            // $attention1 = Db::name('attention')->where(['user_id' => $this->member['id']])->column('to_user');
            // $attention2 = Db::name('attention')->where(['to_user' => $this->member['id']])->column('user_id');
            // $defend = Db::name('user_defend')->where(['to_user' => $this->member['id']])->column('user_id');

            if ($this->member['quality'] < 2 && $this->member['sex'] == '女') {
                $todayGreetCount = Db::name('privatechat')->where(['userid'=>$this->member['id'], 'type'=>8, 'content'=>'[礼物]'])->whereTime('addtime', 'today')->count();

                // if ($todayGreetCount >= 30) {
                //     return $this->miss('打招呼频繁,休息一下吧');
                // }
            }
            $current_time = time();
            $is_public = 0;
            if (!($this->member['entertainment'] == 0 && $this->member['sex'] == '女')) {
                // $sayhiNum = 10;
                // if ($this->member['noble_grade'] && $this->member['noble_time'] > $current_time) {
                //     $privilege = Db::name('grade_noble')->where(['grade' => $this->member['noble_grade']])->value('privilege');
                //     $privilege = explode(',', $privilege);
                //     if (in_array(17, $privilege)) {
                //         $sayhiNum = 50;
                //     }
                // }

                // $fates = Db::name('privatechat')->where(['userid'=>$this->member['id'], 'is_fate'=>1, 'is_public'=>1, 'front_id'=>['gt', 0], 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->column('touserid');
                // $fates = array_unique($fates);
                // if (sizeof($fates) >= $sayhiNum && !in_array($id, $fates)) {
                //     return $this->miss('今日打招呼次数已达上限');
                // }
                $is_public = 1;
            } else {
                // $fates = Db::name('privatechat')->where(['userid'=>$this->member['id'], 'is_fate'=>1, 'front_id'=>['gt', 0], 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->column('touserid');
                // $fates = array_unique($fates);

                switch (intval($this->member['quality'])) {
                    case 0:
                    case 1:
                    case 2:
                        $sayhiCount = 50;
                        break;
                    case 3:
                        $sayhiCount = 100;
                        break;
                    
                    default:
                        $sayhiCount = 150;
                        break;
                }
                
                // if (sizeof($fates) >= $sayhiCount && !in_array($id, $fates)) {
                //     return $this->miss('今日打招呼次数已达上限');
                // }
            }

            $money = 0;
            // foreach ($ids as $v) {
            //     if ($v != $kefu) {
            //         if (isset($touserConfig[$v]) && ($touserConfig[$v] + 0)) {

            //         } else {
            //             $touserConfig[$v] = 1;
            //         }

            //         if (!in_array($v, $attention1) || !in_array($v, $attention2)) {
            //             if (!in_array($v, $defend)) {
            //                 if ($this->member['sex'] == '男') {
            //                     $money += $touserConfig[$v];
            //                 }

            //                 if ($speed) {
            //                     $money += 1;
            //                 }
            //             }
            //         }
            //     }
            // }

            // if ($this->member['volley'] < $money) {
            //     return $this->return['user.error.insufficientBalance'];
            // }

            // if ($speed) {
            //     $money = count($ids);

            //     if ($this->member['volley'] < $money) {
            //         return $this->return['user.error.insufficientBalance'];
            //     }

            //     Balance::index($this->member['id'], $money, '同城速配');
            // } else {
            //     // 任务
            //     Task::finish('greet', $this->member['id']);
            // }

            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

            // $types = $this->member['sex'] == '男' ? 1 : 2;

            // if ($speed) {
            //     $default = Db::name('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $this->member['id']]]])->orderRaw('rand()')->find();

            //     if (!$default) {
            //         $default = Db::name('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->orderRaw('rand()')->find();
            //         $default['channel'] = 2;
            //     }
            // } else {
            //     $default = Db::name('gift')->where(['types' => 0])->orderRaw('rand()')->find();
            // }
             $default = Db::name('gift')->where(['types' => 0])->orderRaw('rand()')->find();
            if ($default) {
                // 心动数+1
                // Db::name('user')->where(['id' => ['in', $ids]])->setInc('heart');

                // 被动聊天不扣费
                /*$chatFreeUsers1 = Db::name('chat_free')->where(['user_id' => $this->member['id'], 'to_user' => ['in', $ids]])->column('to_user');

                $chatFreeUsers2 = Db::name('chat_free')->where(['user_id' => ['in', $ids], 'to_user' => $this->member['id']])->column('user_id');

                $inserts = [];
                $current_time = time();
                foreach ($ids as $item) {
                    if (!in_array($item, $chatFreeUsers1) && !in_array($item, $chatFreeUsers2)) {
                        $inserts[] = ['user_id' => $item, 'to_user' => $this->member['id'], 'create_time' => $current_time];
                    }
                }

                if ($inserts) {
                    Db::name('chat_free')->insertAll($inserts);
                }*/
                
                    //   $greetInfo = Db::name('privatechat_greet')->where(['user_id' => $this->member['id']])->select();
                       
                       
                       
                       
        //     $greetInfoSql = "(SELECT * FROM privatechat_greet WHERE channel = 1 and status =1 and  user_id ={$this->member['id']}  ORDER BY RAND() LIMIT 1)
        // UNION ALL
        // (SELECT * FROM privatechat_greet WHERE channel = 2 and status =1 and  user_id ={$this->member['id']} ORDER BY RAND() LIMIT 1)
        // UNION ALL
        // (SELECT * FROM privatechat_greet WHERE channel = 3 and status =1 and  user_id ={$this->member['id']} ORDER BY RAND() LIMIT 1)";
        //         $greetInfo = Db::query($greetInfoSql);
                       
                  
                  
                  
                $greet1 = Db::name('privatechat_greet')->where(['channel'=>1,'status'=>1,'user_id'=>(int)$this->member['id']])->order('id','desc')->limit(1)->select() ;
                $greet2 = Db::name('privatechat_greet')->where(['channel'=>2,'status'=>1,'user_id'=>(int)$this->member['id']])->order('id','desc')->limit(1)->select() ;
                $greet3 = Db::name('privatechat_greet')->where(['channel'=>3,'status'=>1,'user_id'=>(int)$this->member['id']])->order('id','desc')->limit(1)->select() ;

                $greetInfo = array_merge($greet3,$greet2,$greet1);     
                       
                if ($greetInfo){
                    foreach ($greetInfo as $key=>$value){
                        if ($value['channel'] ==1){
                            //语音
                            $datas = [
                                'userid' => $this->member['id'],
                                'touserid' => $id,
                                'type' => 2,
                                'content' => $value['content'],
                                'timing' => 1,
                                'greet' => 1,
                                'speed' => 1,
                                'second' => $value['voice_time'],
                                'finish' => 1,
                            ];
                        }elseif ($value['channel'] ==2){
                            //文字
                            $datas = [
                                'userid' => $this->member['id'],
                                'touserid' => $id,
                                'type' => 0,
                                'content' => $value['content'],
                                'return' => 0,
                                'second' => 0,
                                'front_id' => time(),
                                'ispayer' =>0,
                            ];
                        }elseif ($value['channel'] ==3){
                            //图片
                            $datas = [
                                'userid' => $this->member['id'],
                                'touserid' => $id,
                                'type' => 1,
                                'content' => $value['content'],
                                'timing' => 1,
                                'greet' => 1,
                                'speed' => 1
                            ];
                        }
                     curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                    }
                    cache('greet' . $this->member['id'], 1, 1);
                    cache('greet'.$this->member['id'].'-to-' . $id, '已经打过招呼', 7200);

                }else{
                    foreach ($ids as $item) {
                        if ($speed) {
                            $datas = [
                                'userid' => $this->member['id'],
                                'touserid' => $item,
                                'type' => $default['channel'] == 1 ? 2 : 0,
                                'content' => $default['content'],
                                'timing' => 1,
                                'greet' => 1,
                                'speed' => 1
                            ];

                            if ($content) {
                                $datas['content'] = $content;
                            }
                        } else {
                            $datas = [
                                'userid' => $this->member['id'],
                                'touserid' => $item,
                                'type' => 8,
                                'id' => $default['id'],
                                'num' => 1,
                                'timing' => 1,
                                'is_public' => $is_public,
                                'from'=>input('from', 1)
                            ];
                        }
                        cache('greet' . $this->member['id'], 1, 1);
                        curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                        cache('greet'.$this->member['id'].'-to-' . $id, '已经打过招呼', 7200);
                    }

                }

                // foreach ($ids as $item) {
                //     if ($speed) {
                //         $datas = [
                //             'userid' => $this->member['id'],
                //             'touserid' => $item,
                //             'type' => $default['channel'] == 1 ? 2 : 0,
                //             'content' => $default['content'],
                //             'timing' => 1,
                //             'greet' => 1,
                //             'speed' => 1
                //         ];

                //         if ($content) {
                //             $datas['content'] = $content;
                //         }
                //     } else {
                //         $datas = [
                //             'userid' => $this->member['id'],
                //             'touserid' => $item,
                //             'type' => 8,
                //             'id' => $default['id'],
                //             'num' => 1,
                //             'timing' => 1,
                //             'is_public' => $is_public,
                //             'from'=>input('from', 1)
                //         ];
                //     }
                //     cache('greet' . $this->member['id'], 1, 1);
                //     curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                // }
            }
        // }

        return $this->return['common.success.default'];
    }

    // 今日缘分 (搬回TP3)
    public function fate(Request $request = null)
    {
        /*if ($request->param('id')) {
            $ids = explode(',', $request->param('id'));

            $types = $this->member['sex'] == '男' ? 1 : 2;

            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

            $content = Db::name('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $this->member['id']]]])->column('content');

            Db::name('user')->where(['id' => $this->member['id']])->setField('zhaohu_time', time());

            if ($content) {
                // 心动数+1
                Db::name('user')->where(['id' => ['in', $ids]])->setInc('heart');

                foreach ($ids as $item) {
                    $datas = [
                        'userid' => $this->member['id'],
                        'touserid' => $item,
                        'type' => 0,
                        'content' => $content[mt_rand(0, count($content) - 1)],
                        'timing' => 1,
                        'fate' => 1,
                    ];
                    curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                }
            }

            return $this->return['common.success.default'];
        } else {
            return $this->return['common.error.default'];
        }*/
    }

    public function loginGreet()
    {
        $kefu = Db::name('config_system')->where(['title' => 'id'])->value('content');
        $kefu = (int)strip_tags($kefu);

        $request = request();

        if ($this->member['is_online'] && (strtotime($this->member['last_login_datetime']) + 10) > time()) {
            $sex = $this->member['sex'] == '男' ? '女' : '男';
            $where = ['id' => ['neq', $kefu], 'sex' => $sex, 'is_online' => 1];

            if ($this->member['sex'] == '男') {
                $where['is_identity_authentication'] = 2;
            }

            $count = mt_rand(20, 30);

            $ids = Db::name('user')->where($where)->orderRaw('rand()')->limit($count)->column('id');
        }

        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

        $types = $this->member['sex'] == '男' ? 1 : 2;

        $default = Db::name('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->orderRaw('rand()')->find();
        $default['channel'] = 2;


        if ($default) {
            foreach ($ids as $item) {

                $datas = [
                    'userid' => $this->member['id'],
                    'touserid' => $item,
                    'type' => $default['channel'] == 1 ? 2 : 0,
                    'content' => $default['content'],
                    'timing' => 1,
                    'greet' => 1,
                    'speed' => 1
                ];

                curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
            }
        }

        return $this->return['common.success.default'];
    }

    // 进入聊天窗口获取双方信息
    public function detail()
    {
        $user_id_real = $user_id = $this->params['user_id'];
        $to_user_real = $to_user = $this->params['to_user'];

        $userWhere = [$user_id, $to_user];
       
        $where = ['id' => ['in', $userWhere]];
        $field = 'id, name, head_100 avatar, age, sex, stature, city, occupation, longitude, latitude, xuni_discount, 
                  is_identity_authentication, realname_auth, free_chat, free_voice, free_video, is_online, yqr, yqm, register_datetime, entertainment, reg, self_slogan,hide_distance,noble_time,is_hide';

        // $users = Db::name('user')->where($where)->column($field);
        
        
        $user1 = Db::name('user')->where(['id'=>(int)$user_id])->field($field)->find();
        $user2 = Db::name('user')->where(['id'=>(int)$to_user])->field($field)->find();
        $users[$user_id] = $user1;
        $users[$to_user] = $user2;
        
        if ($users[$user_id]['reg'] != $users[$to_user]['reg']) {
            return $this->miss('参数异常');
        }

        $data = ['self' => [], 'another' => [], 'data' => []];

        if (isset($users[$user_id])) {
            $data['self'] = $users[$user_id];
        }

        if ($data['self'] && isset($users[$to_user])) {
            // $blacklist = Db::name('blacklist')->where([
            //     'user_id' => $user_id,
            //     'to_user' => $to_user,
            // ])->cache('black' . $user_id . '_' . $to_user)->value('id');
            // $attention = Db::name('attention')->where([
            //     'user_id' => $user_id,
            //     'to_user' => $to_user,
            // ])->cache('follow' . $user_id . '_' . $to_user)->value('id');

            // $data['data']['blacklist'] = $blacklist ? 1 : 0;
            // $data['data']['attention'] = $attention ? 1 : 0;

            $couple_a = $user_id < $to_user ? $user_id . ',' . $to_user : $to_user . ',' . $user_id;
            $intimate = Db::name('user_intimate')->where(['couple_a' => $couple_a])->value('intimate');

            //$data['data']['intimate'] = $intimate/10 ?: 0;
            $data['data']['intimate'] = $intimate ? $intimate / 10 : 0;

            $configPersonal = Db::name('config_personal')->where(['user_id' => $to_user_real])->find();
            $config = Db::name('config_system')->where(['category' => ['in', ['chat', 'kefu', 'user']]])->cache(3600)->column('title, content');

            if ($users[$to_user]['sex'] == '女') {
                /*$distance = bothDistance($users[$user_id]['latitude'],$users[$user_id]['longitude'], $users[$to_user]['latitude'],$users[$to_user]['longitude']);

                if (isset($configPersonal['hide_distance']) && ($configPersonal['hide_distance']+ 0)) {
                    $users[$to_user]['distance'] = '保密';
                    $users[$to_user]['city'] = '保密';
                } else {
                    $distance = $users[$to_user]['xuni_discount'] + 0 ? $users[$to_user]['xuni_discount'] : $distance;
                    $users[$to_user]['distance'] = $distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm';
                }

                if ($config['hide_city'] + 0) {
                    $users[$to_user]['city'] = '保密';
                }*/

                $users[$to_user]['city'] = '';

                /*$photos = Db::name('user_img')->where(['types' => 1, 'user_id' => $to_user, 'status' => 1])->order('id desc')->limit(3)->cache(60)->column('picthumb');

                if ($photos) {
                    foreach ($photos as $key => $item) {
                        $item = json_decode($item, true)[0];
                        $photos[$key] = changeUrl($item);
                    }
                } else {
                    $photos = [];
                }

                $users[$to_user]['photos'] = $photos;*/

                $users[$to_user]['photos'] = [];

            }

            $users[$to_user]['chat_price'] = $config['chat_price_switch'] > 0 ? $config['chat_price'] : $configPersonal['chat_price'];
            $users[$to_user]['voice_switch'] = $configPersonal['voice_switch'];
            $users[$to_user]['voice_price'] = $config['voice_price_switch'] > 0 ? $config['voice_price'] : $configPersonal['voice_price'];
            $users[$to_user]['video_switch'] = $configPersonal['video_switch'];
            $users[$to_user]['video_price'] = $config['video_price_switch'] > 0 ? $config['video_price'] : $configPersonal['video_price'];

            // 聊天打折
            $overpayscale = 0;
            // 获取所有关联账号的总支付
            // $overpayscale = UserIntimateService::Count($this->member['id'], $to_user, true);
            // if ($overpayscale) {
            //     $chat_scale['scale'] = $overpayscale;
            // } else {
            //     $chat_scale = Db::name('limit_chat_price')->where($this->member['id']>$to_user ? 'user_id='.$to_user. ' and another_id='. $this->member['id'] : 'user_id='.$this->member['id']. ' and another_id='. $to_user)->find();
            // }
            // if ($chat_scale) {
            //     $users[$to_user]['chat_price'] = isset($users[$to_user]['chat_price']) ? round($users[$to_user]['chat_price'] * $chat_scale['scale'] / 100, 2) : 0;
            //     $users[$to_user]['voice_price'] = isset($users[$to_user]['voice_price']) ? round($users[$to_user]['voice_price'] * $chat_scale['scale'] / 100, 2) : 0;
            //     $users[$to_user]['video_price'] = isset($users[$to_user]['video_price']) ? round($users[$to_user]['video_price'] * $chat_scale['scale'] / 100, 2) : 0;
            // }

            //活动打折
            // $chat_discount = Db::name('act_chat_discount_user')->where(['user_id'=>$to_user,'state'=>0, 'starttime'=>['<=', datetime()], 'endtime'=>['>=', datetime()]])->fetchSql(false)->find();
            $data['is_chat_discount'] = false;
            // if ($chat_discount) {
            //     $data['is_chat_discount'] = (floatval($chat_discount['discount']) / 10) . '折';
            //     $users[$to_user]['chat_price'] = number_format($users[$to_user]['chat_price'] * $chat_discount['discount'] / 100, 2);
            //     $users[$to_user]['voice_price'] = number_format($users[$to_user]['voice_price'] * $chat_discount['discount'] / 100, 2);
            //     $users[$to_user]['video_price'] = number_format($users[$to_user]['video_price'] * $chat_discount['discount'] / 100, 2);
            // }

            unset($data['self']['xuni_discount'], $data['self']['longitude'], $data['self']['latitude'], $data['self']['realname_auth'],
                $data['self']['is_identity_authentication'], $data['self']['occupation'], $data['self']['city'], $data['self']['stature'],
                $users[$to_user]['free_chat'], $users[$to_user]['free_voice'], $users[$to_user]['free_video'], $users[$to_user]['xuni_discount'],
                $users[$to_user]['longitude'], $users[$to_user]['latitude']);

            $data['self']['avatar'] = changeUrl($data['self']['avatar']);
            $users[$to_user]['avatar'] = changeUrl($users[$to_user]['avatar']);
            //新增返回是否为会员
            $users[$to_user]['is_vip'] = $users[$to_user]['noble_time'] >= time() ? 1 : 0; //判断会员

            $data['another'] = $users[$to_user];




            $kefu = intval($config['id']);
            $data['data']['kefu'] = ($kefu == $user_id || $kefu == $to_user) ? 1 : 0;

            $topChat = Db::name('top_chat')->where(['types' => 1, 'uid' => $user_id, 'to_uid' => $to_user])->cache(3600)->find();
            $data['data']['topChat'] = $topChat ? 1 : 0;

            /*$user_labels = Labels::lists([$to_user]);

            $data['data']['labels'] = $user_labels[$to_user] ?? [];*/

            $data['data']['labels'] = [];
        }


        foreach ($data as $key => $item) {
            if (!$item) {
                $data[$key] = (object)[];
            }
        }


        $ChatChargeRecordsMap = [
            'user_id' => $to_user_real,
            'another_id' => $user_id_real,
        ];
        $ChatChargeRecordsField = 'user_remark';
        if ($user_id_real < $to_user_real) {
            $ChatChargeRecordsMap = [
                'user_id' => $user_id_real,
                'another_id' => $to_user_real,
            ];
            $ChatChargeRecordsField = 'another_remark';
        }

        $data['payer'] = 0;
        $data['paystate'] = 0;
        $data['invite'] = 0;
        $data['show_changepay_btn'] = 0;
        $data['show_win'] = 0;
        // $data['another']['is_online'] = 0;
        $config = Db::name('config_system')->where(['category'=>'two_way_charge'])->column('title,content');
        $ChatDetail = Db::name('chat_charge_records')->where($ChatChargeRecordsMap)->find();
        // $ChatList = Db::name('chat_lists')->where($ChatChargeRecordsMap)->find();
        // $data['chat_from'] = $ChatList['from']??1;
         $data['chat_from'] = 1;
        if ($ChatDetail){
            if ($ChatDetail[$ChatChargeRecordsField]) {
                $data['another']['name'] = $data['self']['reg'] == 2 ? "" : $ChatDetail[$ChatChargeRecordsField];
            }
            $data['payer'] = $ChatDetail['payer'];
            $data['paystate'] = $ChatDetail['state'];
            if ($ChatDetail['state']) {
                $data['show_win'] = 0;
            } else {
                // $data['show_win'] = $ChatDetail['payer'] == 0 || $ChatDetail['payer'] == $data['self']['id'] ? ($data['self']['sex'] == '男' ? 2 : 1) : 0;
                if ($ChatDetail['payer'] == 0) {
                    $data['show_win'] = $data['self']['sex'] == '男' ? 2 : 0;
                } else {
                    $data['show_win'] = $ChatDetail['payer'] == $user_id_real ? ($data['self']['sex'] == '男' ? 2 : 1) : 0;
                }
            }
        } else {
            $data['show_win'] = $data['self']['sex'] == '男' ? 0 : 1;
            if ($users[$user_id_real]['yqr'] && $users[$user_id_real]['yqr'] == $users[$to_user_real]['yqm']) {
                $data['show_win'] = 0;
                $data['invite'] = 2;
                $data['payer'] = $user_id_real;
            } else if ($users[$user_id_real]['yqm'] && $users[$user_id_real]['yqm'] == $users[$to_user_real]['yqr']) {
                $data['show_win'] = 0;
                $data['invite'] = 1;
                $data['payer'] = $to_user_real;
            }
        }
        if ($config['two_way_charge_status'] == 0) {
            $data['show_win'] = 0;
            $data['payer'] = $users[$user_id_real]['sex']=='男'?$user_id_real:$to_user_real;
            return $this->pass($data);
        }
        $data['show_changepay_btn'] = 1;
        if ($data['self']['sex'] == '男') {
            if (strtotime($config['two_way_charge_reg_time']) > strtotime($users[$user_id_real]['register_datetime'])) {
                $data['show_changepay_btn'] = 0;
                $data['show_win'] = 0;
                $data['payer'] = $user_id_real;
            }
        } elseif (strtotime($config['two_way_charge_reg_time']) > strtotime($users[$to_user_real]['register_datetime'])) {
            $data['payer'] = $to_user_real;
            $data['show_win'] = 0;
        }


        // $timenow = time();
        // $privatechat_free = Db::name('privatechat_free')
        //                         ->where(($user_id>$to_user?"user_id=$to_user and another_id=$user_id":"user_id=$user_id and another_id=$to_user") . " and ((end_time=0 or start_time=0 or end_time>$timenow) or ((server=$user_id and confirm in (1,2)) or (server=$to_user and confirm in (1,3))))")
        //                         ->order('id asc')
        //                         ->field('id,user_id,another_id,server,order_sn,create_time,start_time,end_time,method,confirm')
        //                         ->find();
        // $privatechat_free = Db::name('privatechat_free')
        //                         ->where(($user_id>$to_user?"user_id=$to_user and another_id=$user_id":"user_id=$user_id and another_id=$to_user") . " and (end_time=0 or start_time=0 or end_time>$timenow)")
        //                         ->order('id asc')
        //                         ->field('id,user_id,another_id,server,order_sn,create_time,start_time,end_time,method,confirm')
        //                         ->find();
        // if ($privatechat_free) {
        //     $privatechat_free['order_info'] = Db::name('order_of_service')->where(['number'=>$privatechat_free['order_sn']])->field('id,title,price,status,type,num')->find();
        // }
        // $data['privatechat_free'] = $privatechat_free ? $privatechat_free : false;
        $data['privatechat_free'] =  false;
        return $this->pass($data);
    }

    public function chatfreeConfirm($id)
    {
        $user_id = $this->member['id'];
        // $user_id = 20093684;
        $chatFree = Db::name('privatechat_free')->where(['id'=>$id])->find();
        if (!$chatFree || !in_array($user_id, [$chatFree['user_id'], $chatFree['another_id']])) {
            return $this->miss('无效操作');
        }
        $res = false;
        if ($chatFree['server'] == $user_id) {
            if (in_array($chatFree['confirm'], [1, 2])) {
                $res = Db::name('privatechat_free')->where(['id'=>$id])->update(['confirm'=>$chatFree['confirm']==1?3:4]);
            }
        } else {
            if (in_array($chatFree['confirm'], [1, 3])) {
                $res = Db::name('privatechat_free')->where(['id'=>$id])->update(['confirm'=>$chatFree['confirm']==1?2:4]);
            }
        }
        if ($res) {
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $chatFree['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $chatFree['another_id']]));
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $chatFree['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $chatFree['user_id']]));
            return $this->miss('操作成功');
        } else {
            return $this->miss('操作失败');
        }
    }

    // ---------------------------------------------

    // 未读数
    public function getreadcount($data)
    {
        $data = json_decode($data, true);

        $user_id = $data['user_id'];

        $user = Db::name('user')->field('sex, register_datetime')->cache(86400)->where(['id' => $user_id])->find();

        $untip1 = Db::name('privatechat')->where(['touserid' => $user_id, 'sound_tip' => 0, 'status' => ['neq', -1], 'isRead' => 0])->count(); # 私聊声音提示
        $unread1 = Db::name('privatechat')->where(['touserid' => $user_id, 'isRead' => 0, 'status' => ['neq', -1]])->count(); # 私聊未读消息数

        $channel = $user['sex'] == '男' ? [1, 2] : [1, 3];
        $message = Db::name('sys_message')->where(['channel' => ['in', $channel], 'type' => 0, 'create_time' => ['egt', $user['register_datetime']]])->limit(10)->column('id');

        if ($message) {
            $read_count = Db::name('sys_message_read')->where(['user_id' => $user_id, 'message_id' => ['in', $message]])->count();
            $unread2 = count($message) - $read_count;
        } else {
            $unread2 = 0;
        }

        $sound_tip = $untip1;
        if ($sound_tip) {
            Db::name('privatechat')->where(['touserid' => $user_id])->setField('sound_tip', 1);

            $code = 200;
            $message = 1;
        } else {
            $code = 400;
            $message = 0;
        }

        $message = json_encode([
            'code' => $code,
            'action' => 'Home/Privatechat/getreadcount',
            'data' => [
                'message' => $message,
                'chat_count' => (int)$unread1,
                'message_count' => (int)$unread2
            ]
        ]);

        Socket::sendToUid($user_id, $message);
    }

    public function changeread()
    {
        $user_id = $this->params['user_id'];
        $to_user = $this->params['to_user'];

        Db::name('privatechat')->where(['userid' => $to_user, 'touserid' => $user_id])->setField('isRead', 1);

        // 清除聊天缓存
        /*S("getMsgList$user_id&$touserid",null);
        S("getMsgList$touserid&$user_id",null);*/

        $message = json_encode([
            'code' => 200,
            'action' => 'Home/Privatechat/changeread',
            'data' => [
                'touserid' => $user_id
            ]
        ]);

        Socket::sendToUid($user_id, $message);
    }

    // 获取最新20条信息
    public function getMsgList(): Json
    {
        $user_id = (int)$this->params['user_id'];
        $to_user = (int)$this->params['to_user'];
        $page = $this->params['page'] ?? 1;
        $pages = 20;

        $type = input('type') ?? false;
        $where = '';
        if ($type === "0" || $type) {
            $where = ' and type='.$type;
        }

        //$cache = $page ? false : S("getMsgList$userid&$touserid");
        $cache = false;

        if ($cache === false) {
            $start = ($page - 1) * $pages;

            $lastTime = date('Y-m-d H:i:s');

            $users = Db::name('user')->where(['id' => ['in', [$user_id, $to_user]]])->cache(86400)->column('id, name, head_100 head_portrait, sex');

            $sql = <<<sql
            select id, type, userid, content, isRead, is_burn, second, status, state, data, score, finish, location  from privatechat
            where
                (userid = $user_id and touserid = $to_user and single <> 1 and status not in (-1,1) $where)
                or (userid = $to_user and touserid = $user_id and single <> 2 and status not in (-1,2) $where)
            order by id desc limit $start, $pages
sql;

            $data = Db::Query($sql);

            if ($data) {
                $ids = implode(',', array_column($data, 'id'));

                $sql = <<<sql
                select *,TIMESTAMPDIFF(SECOND,addtime,NOW()) AS second,
                    TIMESTAMPDIFF(MINUTE,addtime,NOW()) as minute,
                    TIMESTAMPDIFF(HOUR,addtime,NOW()) as hour,
                    TIMESTAMPDIFF(DAY,addtime,NOW()) as day,
                    TIMESTAMPDIFF(WEEK,addtime,NOW()) as week
                from privatechat where id in ($ids)
sql;
                $result = Db::Query($sql);

                $rows = [];
                foreach ($result as $item) {
                    $rows[$item['id']] = $item;
                }

                $updates = [];
                foreach ($data as $key => $item) {

                    if (!$item['isRead'] && $item['userid'] != $user_id) {
                        $updates[] = $item['id'];
                    }

                    $data[$key]['name'] = $users[$item['userid']]['name'];
                    $data[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                    $data[$key]['self'] = $item['userid'] == $user_id ? 1 : 0;

                    $row = $rows[$item['id']];

                    $addtime = $row['addtime'];

                    $data[$key]['addtime'] = $second = floor(strtotime($lastTime) - strtotime($addtime));
                    $data[$key]['showtime'] = $second > 300;
                    $lastTime = $addtime;

                    if ($row['week'] > 1) {
                        $data[$key]['time'] = $row['addtime'];
                    } elseif ($row['week'] == 1) {
                        $data[$key]['time'] = '1周前';
                    } elseif ($row['day'] > 0) {
                        $data[$key]['time'] = $row['day'] . '天前';
                    } elseif ($row['hour'] > 0) {
                        $day = strtotime($row['addtime']) < strtotime(date('Ymd')) ? '昨天' : '';
                        $data[$key]['time'] = $day . " " . date('H:i', strtotime($addtime));
                    } elseif ($row['minute'] > 0) {
                        $data[$key]['time'] = $row['minute'] >= 10 ? date('H:i', strtotime($addtime)) : $row['minute'] . '分钟前';
                    } elseif ($row['second'] > 0) {
                        $data[$key]['time'] = $row['second'] . '秒前';
                    }

                    $data[$key]['type'] = $item['type'] == -2 ? 0 : $item['type'];

                    $datas = json_decode($item['data'], true);
                    if (isset($datas['image'])) {
                        $datas['image'] = changeUrl($datas['image']);
                    }

                    if($item['type'] != 13){
                        $datas['cover'] = $datas['cover'] ?? '';
                    }
                    $data[$key]['data'] = $datas;

                    if (in_array($item['type'], [9, 10])) {
                        if (isset($datas['status']) && $datas['status']) {
                            if (isset($datas['start']) && isset($datas['end'])) {
                                $chat_time = $datas['end'] - $datas['start'];
                                $data[$key]['chat_time'] = changeTimeLen($chat_time);
                            } else {
                                if (isset($datas['second']) && $datas['second']) {
                                    $data[$key]['content'] .= changeTimeLen($datas['second'] * 60);
                                } else {
                                    $data[$key]['content'] .= '01:00';
                                }
                            }
                        } else {
                            $data[$key]['content'] .= ' 未接通';
                        }
                    } else if ($item['type'] == 11) {
                        $data[$key]['content'] = changeUrl($item['content']);
                    }
                }

                $ids = array_column($data, 'id');
                array_multisort($ids, SORT_ASC, $data);

                if ($updates) {
                    Db::name('privatechat')->where(['id' => ['in', $updates]])->setField('isRead', 1);

                    if ($data) {
                        if ($user_id != 5559516 && $to_user != 5559516 && $users[$user_id]['sex'] == '男' && $users[$to_user]['sex'] == '女') {
                            $data_count = count($ids);
                            if ($data_count == 1 || (isset($data[$data_count - 1]['showtime']) && $data[$data_count - 1]['showtime'])) {
                                $contain_tip = ['userid' => $user_id, 'touserid' => $to_user, 'type' => -1, 'single' => 1, "content" => '对方查看了你的消息', 'finish' => 1, 'is_public' => 1];
                                Db::name('privatechat')->insert($contain_tip);
                            }
                        }
                    }
                }
            }

            /*if (!$page) {
                S("getMsgList$userid&$touserid",$data,3600);
            }*/
        } else {
            $data = $cache;
        }

        return $this->pass($data);
    }

    // 获取信息列表
    public function getOtherList($data)
    {
        exit;
        $data = json_decode($data, true);

        $user_id = $data['user_id'];
        $oldcount = $data['count'] ?? '';
        $type = $data['type'] ?? '';

        $allcount = 0;

        $user = Db::name('user')->field('sex')->where(['id' => $user_id])->cache(86400)->find();

        if ($user['sex'] == '女') {
            $unread_uid = Db::name('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $user_id, 'isRead' => 0])->column('touserid');

            if ($unread_uid) {
                $where = ['userid' => ['in', $unread_uid], 'touserid' => $user_id];
                $chat_uid = Db::name('privatechat')->where('(type <> -1 or is_public = 1) and (single <> 1 or is_public = 1)')->where($where)->column('userid');

                $chat_uid = $chat_uid ?: [];
            } else {
                $chat_uid = [];
            }

            $not_reply = implode(',', array_diff($unread_uid, $chat_uid)) ?: 0;

            $sql = <<<sql
            (SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and userid not in ($not_reply) and touserid = $user_id and status <> -1 GROUP BY userid)
            UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $user_id and touserid not in ($not_reply) and status <> -1 GROUP BY touserid)
sql;

        } else {
            $sql = <<<sql
            (SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and touserid = $user_id and status <> -1 GROUP BY userid)
            UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $user_id and status <> -1 GROUP BY touserid)
sql;
        }

        $result = Db::Query($sql);

        $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->column('title, content');

        // 家族
        $gresult = [];
        if (intval($config['family_switch'])) {
            $sql = "select t1.*, t2.name, t2.logo sumb_headimg from cluster_user t1, cluster t2 where t1.user_id = $user_id and t2.types = 1 and t1.status = 1 and t2.id = t1.cluster_id";
            $glist = Db::Query($sql);

            $cluster_ids = array_column($glist, 'cluster_id');

            $clusterChats = Db::name('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->column('cluster_id, id, type, content, addtime');
            $talkcounts = Db::name('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->group('cluster_id')->column('cluster_id, count(*) count');

            for ($i = 0; $i < sizeof($glist); $i++) {
                $talkcount = $talkcounts[$glist[$i]['cluster_id']] ?? 0;

                if ($talkcount > 0) {
                    $glist[$i]['is_cluster'] = 1;
                    $glist[$i]['cluster_types'] = 1;

                    $talkone = $clusterChats[$glist[$i]['cluster_id']];

                    $glist[$i]['kefu'] = 0;
                    $glist[$i]['id'] = $talkone['id'];
                    $glist[$i]['touserid'] = $talkone['cluster_id'];
                    $glist[$i]['content'] = $talkone['content'];
                    $glist[$i]['sort_field'] = strtotime($talkone['addtime']);
                    $glist[$i]['addtime'] = time_tran($talkone['addtime']);

                    $count2 = Db::Query("select count(*) as count from clusterchat where cluster_id=" . $glist[$i]['cluster_id'] . " and find_in_set($user_id, isRead)");

                    $count = $talkcount - $count2[0]['count'];

                    $allcount = $allcount + $count;
                    $glist[$i]['count'] = $count;

                    $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                    if (isset($channel[$talkone['type']])) {
                        $glist[$i]['content'] = $channel[$talkone['type']];
                    }

                    array_push($gresult, $glist[$i]);
                }
            }
        }


        $kefu = intval($config['id']);

        $ids = array_column($result, 'id');
        $uids = array_column($result, 'userid');
        $chats = Db::name('privatechat')->where(['id' => ['in', $ids]])->cache(86400)->column('id, single, content, userid, touserid, status, state, type, isRead, addtime');
        $users = Db::name('user')->where(['id' => ['in', $uids], 'delete_time' => 0])->column('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, is_online');
        //$personals = M('config_personal')->where(['user_id' => ['in', $uids]])->getField('user_id, hide_distance, id');
        $delChat = Db::name('del_chat')->where(['uid' => $user_id])->column('to_uid');
        $gradeNoble = Db::name('grade_noble')->where(['id' => ['gt', 0]])->cache(86400)->column('id, icon, circle');

        $userIds = [];
        foreach ($result as $k => $v) {
            $userIds[] = $v['userid'] == $user_id ? $v['touserid'] : $v['userid'];
        }

        $counts = Db::name('privatechat')
            ->where('(type <> -1 or is_public = 1)')
            ->where(['userid' => ['in', $userIds], 'touserid' => $user_id, 'status' => ['not in', [-1, 2]], 'isRead' => 0])
            ->group('userid, touserid')
            ->column('CONCAT_WS("+", userid, touserid), COUNT(*) AS count');

        $del = [];
        foreach ($result as $k => $v) {
            if (in_array($v['userid'], $delChat)) {
                unset($result[$k]);
            } else {
                if (isset($users[$v['userid']]) && isset($chats[$v['id']])) {
                    $chat = $chats[$v['id']];
                    $user = $users[$v['userid']];

                    if ($v['userid'] == $user_id) {
                        $count = $counts[$v['touserid'] . '+' . $user_id]['count'] ?? 0;
                    } else {
                        $count = $counts[$v['userid'] . '+' . $user_id]['count'] ?? 0;
                    }

                    $result[$k]['content'] = $chat['content'];
                    $result[$k]['single'] = $chat['single'];
                    $result[$k]['touserid'] = $chat['touserid'];
                    $result[$k]['status'] = $chat['status'];
                    $result[$k]['state'] = $chat['state'];
                    $result[$k]['type'] = $chat['type'];
                    $result[$k]['sort_field'] = strtotime($chat['addtime']);
                    //$result[$k]['addtime'] = strtotime($chat['addtime']) >= strtotime(date('Ymd')) ? date('H:i', strtotime($chat['addtime'])) : $chat['addtime'];

                    if (strtotime($chat['addtime']) >= strtotime(date('Ymd'))) {
                        $result[$k]['addtime'] = date('H:i', strtotime($chat['addtime']));
                    } else if (strtotime($chat['addtime']) >= (strtotime(date('Ymd')) - 86400)) {
                        $result[$k]['addtime'] = '昨天';
                    } else {
                        $result[$k]['addtime'] = date('Y/m/d', strtotime($chat['addtime']));
                    }
                    $result[$k]['name'] = $user['name'];
                    $result[$k]['sex'] = $user['sex'];
                    $result[$k]['age'] = $user['age'];
                    $result[$k]['is_online'] = $user['is_online'];

                    /*if (isset($personals[$v['userid']]['hide_distance']) && $personals[$v['userid']]['hide_distance']) {
                        $result[$k]['city'] = '';
                    } else {
                        $result[$k]['city'] = $user['city'];
                    }

                    if ($config['hide_city'] && $user['sex'] == '女') {
                        $result[$k]['city'] = '';
                    }*/

                    $result[$k]['city'] = '';

                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_circle'] = $gradeNoble[$user['noble_grade']] ? $gradeNoble[$user['noble_grade']]['circle'] : '';
                    } else {
                        $result[$k]['noble_circle'] = '';
                    }

                    $result[$k]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                    $result[$k]['is_identity_authentication'] = $user['is_identity_authentication'];
                    $result[$k]['sumb_headimg'] = $user['head_100'];
                    $result[$k]['count'] = $count;
                    $result[$k]['isRead'] = $chat['isRead'];
                    $result[$k]['is_cluster'] = 0;
                    $result[$k]['cluster_types'] = 0;


                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_icon'] = $gradeNoble[$user['noble_grade']] ?? '';
                    } else {
                        $result[$k]['noble_icon'] = '';
                    }

                    $allcount = $allcount + $count;

                    $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                    if (isset($channel[$result[$k]['type']])) {
                        $result[$k]['content'] = $channel[$result[$k]['type']];

                        if ($result[$k]['type'] == 11) {
                            $result[$k]['content'] = changeUrl($result[$k]['content']);
                        }
                    } else if ($result[$k]['type'] == -1) {
                        switch ($result[$k]['status']) {
                            case 0:
                                if ($result[$k]['state'] == 1) {
                                    if ($chat['userid'] != $user_id) {
                                        $name = Db::name('user')->where(['id' => $chat['userid']])->value('name');
                                        $result[$k]['content'] = '"' . $name . '"领取了你的红包';
                                    } else {
                                        $name = Db::name('user')->where(['id' => $chat['touserid']])->value('name');
                                        $result[$k]['content'] = '你已领取"' . $name . '"的红包';
                                    }
                                }
                                break;
                            case 3:
                                if ($chat['userid'] == $user_id) {
                                    $result[$k]['content'] = '你撤回了一条消息';
                                } else {
                                    $name = Db::name('user')->where(['id' => $chat['userid']])->value('name');
                                    $result[$k]['content'] = '"' . $name . '"撤回了一条消息';
                                }
                                break;
                        }
                    } else {
                        //if ($result[$k]['single'] && $result[$k]['userid'] != $kefu) {
                        if (false) {
                            if ($user['sex'] == '男') {
                                $result[$k]['content'] = '[回复消息得奖励]';
                            }
                        } else {
                            if (in_array($result[$k]['type'], [5, 7]) && in_array($result[$k]['state'], [0, 2])) {
                                $result[$k]['content'] = '[红包]' . $result[$k]['content'];
                            }
                            switch ($result[$k]['status']) {
                                case 1:
                                    if ($chat['userid'] == $user_id) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                case 2:
                                    if ($chat['touserid'] == $user_id) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                default :
                                    break;
                            }
                        }
                    }
                } else {
                    unset($result[$k]);

                    $del[] = $v['userid'];
                }
            }
        }

        if ($del) {
            Db::name('privatechat')->where(['userid|touserid' => ['in', $del]])->delete();
        }

        if ($type == 0 || $allcount != $oldcount) {
            $result = array_merge($result, $gresult);

            // 去除重复项，将最新聊天顶上去
            if ($result) {
                array_multisort(array_column($result, 'sort_field'), SORT_DESC, $result);

                $con = [];
                $arr = [];
                foreach ($result as $k => $v) {
                    if (!in_array($v['userid'], $arr)) {
                        $con[$k] = $v;
                        $arr[$k] = $v['userid'];

                        $con[$k]['top'] = 0;
                        $con[$k]['sort'] = 0;
                    }
                }
                $result = array_values($con);

                $tops_chat = Db::name('top_chat')->where(['types' => 1, 'uid' => $user_id])->order('id asc')->column('to_uid');
                //$tops_cluster = M('top_chat')->where(['types' => 2, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                $tops_cluster = [];

                if ($tops_chat || $tops_cluster) {
                    $con1 = [];
                    $con2 = [];
                    foreach ($result as $k => $v) {

                        $tops = $v['is_cluster'] ? $tops_cluster : $tops_chat;

                        if ($v['is_cluster']) {
                            $tops = $tops_cluster;
                            $tops_field = 'cluster_id';
                        } else {
                            $tops = $tops_chat;
                            $tops_field = 'userid';
                        }

                        if (in_array($v[$tops_field], $tops)) {
                            $v['top'] = 1;
                            $v['sort'] = array_search($v[$tops_field], $tops);
                            $con1[] = $v;
                        } else {
                            $con2[] = $v;
                        }
                    }

                    if ($con1) {
                        $tmp = array_column($con1, 'sort');
                        array_multisort($tmp, SORT_DESC, $con1);
                    }

                    $result = array_merge($con1, $con2);
                }
            }

            //array_multisort(array_column($result, 'addtime'), SORT_DESC, $result);

            if ($user_id != $kefu) {
                $kefus = [];
                $contain1 = [];
                $contain2 = [];
                foreach ($result as $key => $item) {
                    if ($item['kefu']) {
                        $item['city'] = '';
                        $kefus[] = $item;
                    } else if (!$item['is_cluster'] && $item['touserid'] == $kefu) {
                        $contain1[] = $item;
                    } else {
                        $contain2[] = $item;
                    }
                }

                $result = array_merge($kefus, $contain1, $contain2);
            }

            foreach ($result as $key => $item) {
                /*$intimate = M('user_intimate')->where(['couple_a|couple_b' => $item['touserid'] . ',' . $userid, 'intimate' => ['gt', 0]])->getField('intimate');

                $result[$key]['intimate'] = $intimate ?: 0;*/

                $result[$key]['intimate'] = 0;
            }

            $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $result, 'count' => $allcount]]);
        } else {
            $data = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getOtherList', 'data' => []]);
        }

        Socket::sendToUid($user_id, $data);
    }

    // 发送信息
    public function addTalk($user_id, $to_user, $type = 0, $content = '', $second = 0, $data = '', $timing = 0, $greet = 0, $system_greet = 0, $login_greet = 0, $single = 0, $fate = 0, $notice = 0)
    {
        exit;
        $content = strip_tags($content);
        $is_burn = $this->params['is_burn'] ?? 0;

        $blacklist = Db::name('blacklist')->where(['user_id' => $to_user, 'to_user' => $user_id])->find();
        if ($blacklist) return $this->miss('你已进入对方黑名单，无法发送消息');

        $userInfo = Db::name('user')->where(['id' => $user_id])->find();
        $touserInfo = Db::name('user')->where(['id' => $to_user])->find();

        if (!$userInfo || !$touserInfo || $userInfo['delete_time'] || $touserInfo['delete_time']) {
            return $this->miss('账号已注销');
        }

        if ($userInfo['is_banned'] && strtotime($userInfo['banned_end_time']) > time()) {
            return $this->miss('当前账号已被冻结');
        }

        $delChat = Db::Query("select * from del_chat where (uid = $user_id and to_uid = $to_user) or (uid = $to_user and to_uid = $user_id)");
        if ($delChat) {
            $del_ids = [$delChat[0]['id']];
            if (isset($delChat[1])) {
                $del_ids[] = $delChat[1]['id'];
            }
            Db::name('del_chat')->where(['id' => ['in', $del_ids]])->delete();
        }

        $config = Db::name('config_system')->where(['category' => ['in', ['kefu', 'chat', 'greet', 'speaker', 'defend']]])->column('title, content');
        $kefu = intval($config['id']);


        if ($kefu != $user_id && $kefu != $to_user) {
            /*if ($touserInfo['sex'] == '男' && $userInfo['sex'] == '女') {
                $touserConfig = ['chat_price' => 0];
            } else {*/
            $touserConfig = Db::name('config_personal')->where(['user_id' => $to_user])->find();

            if (!$touserConfig) {
                $touserConfig = ['chat_price' => $config['chat_price']];
            } else {
                $touserConfig = $config['chat_price_switch'] > 0 ? ['chat_price' => $config['chat_price']] : $touserConfig;
            }
            //}
        } else {
            $touserConfig = ['chat_price' => 0];
        }


        $free = 0;

        $status = 0;  // 好友关系或守护关系
        $money = 0;
        if (!in_array($kefu, [$user_id, $to_user]) || !$greet) {
            if (!in_array($type, [9, 10])) {
                if ($touserConfig['chat_price'] + 0) {
                    /*$attention1 = M('attention')->where(['user_id' => $userid, 'to_user' => $touserid])->find();
                    $attention2 = M('attention')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                    if (!$attention1 || !$attention2) {
                        $defend = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid, 'angel' => 1])->find();
                        if (!$defend) {
                            $status = 1;
                        }
                    }*/

                    $status = 1;
                }
            }
        }

        $chat_free = 0;

        //  其中一方属于系统推送过来的，只有男方是需要付费。否则，谁先发起对话，双方费用需都承担
        if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
            /*$greetRecords = M()->Query("select id from greet_records where (user_id=$touserid and to_user=$userid) or (user_id=$userid and to_user=$touserid)");
            $greetRecords = false;

            if ($greetRecords) {
                $status = 0;
                $recharge_user = $touserInfo;
            } else {
                $recharge_user = $userInfo;
            }*/
            $recharge_user = $touserInfo;
            $chat_free = 1;
        } else {
            $recharge_user = $userInfo;
        }

        switch ($type) {
            case 0:
                if ($content == '') return $this->miss('内容不能为空');

                if (!$timing) {
                    // 敏感词检测
                    $contain = Db::name('filter_word')->where(['state' => 1])->cache(3600)->column('name');
                    foreach ($contain as $v) {
                        if (stripos($content, $v) !== false) {
                            return $this->miss('消息含有敏感词"' . $v . '",请重新编辑发送');
                        }
                    }

                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $user_id && $kefu != $to_user) { // 非客服咨询
                        /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                            $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                            if (!$chatRecord) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                if ($chatRecord) {
                                    $extraMoney = 1;
                                }
                            }
                        }*/
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = Db::name('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = Db::name('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                Db::name('grade_noble_use')->insert(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {
                                    /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                    if ($chatCount >= $config['chat_count']) {
                                        exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                    } else {
                                        M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                        $money = 0;
                                    }*/

                                    Db::name('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    if ($recharge_user['volley'] < $money) {
                                        if ($recharge_user['id'] == $user_id) {
                                            return $this->miss('余额不足，无法发送消息', 300);
                                        } else {
                                            return $this->miss('对方余额不足，无法发送消息');
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;

                        if ($recharge_user['id'] == $user_id) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                    }

                    // 添加聊天
                    $id = Db::name('privatechat')->insert($contain);
                    // 更新会话列表
                    //D('ChatLists')->updateLists($userid, $touserid, 0, 0, $content);

                    // 预警词记录
                    if ($kefu != $user_id) {
                        $warnWord = Db::name('chat_warn_word')->where(['is_hidden' => 0])->cache(60)->column('id, title');
                        foreach ($warnWord as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                Db::name('chat_warn')->insert(['user_id' => $user_id, 'word_id' => $k, 'chat_id' => $id, 'create_time' => time()]);
                                break;
                            }
                        }
                    }

                    if ($extraMoney) {
                        $rewardContent = '🎉🎉 恭喜，你的魅力吸引了小哥哥<br>👄 24小时内回复消息还可额外获得金币<br><br>上传更多照片能获得更多搭讪和积分哦~';
                        $contain_1 = ["userid" => $user_id, "touserid" => $to_user, "type" => -1, 'single' => 1, "content" => $rewardContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                        Db::name('privatechat')->insert($contain_1);
                    }
                } else {
                    $location = I('location');  // 带有跳转链接

                    if ($location) {
                        $datas = I('data');
                        $datas = htmlspecialchars_decode($datas);
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'location' => $location, 'data' => $datas, 'finish' => 1];
                        Db::name('privatechat')->insert($contain);
                    } else {
                        $speed = intval(I('speed'));  // 速配
                        $match = intval(I('match'));  // 夫妻相
                        //$fate = intval(I('fate'));  // 今日缘分

                        if ($speed) {
                            $types = $userInfo['sex'] == '男' ? 2 : 1;

                            $content_default = Db::name('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $to_user]]])->order('rand()')->value('content');

                            if (!$content_default) {
                                $content_default = Db::name('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->order('rand()')->value('content');
                            }
                            $speedContent = '❤ 同城速配成功，快把握住缘分吧~';
                            $contain_1 = ["userid" => $user_id, "touserid" => $to_user, "type" => 0, 'single' => 1, "content" => $content];
                            $contain_2 = ["userid" => $to_user, "touserid" => $user_id, "type" => 0, 'single' => 1, "content" => $content_default];
                            $contain_3 = ["userid" => $to_user, "touserid" => $user_id, "type" => -1, 'single' => 1, "content" => $speedContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                            Db::name('privatechat')->insert($contain_1);
                            Db::name('privatechat')->insert($contain_2);
                            Db::name('privatechat')->insert($contain_3);
                        } else if ($match) {
                            $matchContent = '👫 经大数据测算，你和对方具有夫妻相<br>👄 赶快向Ta打个招呼，把握缘分哦~';
                            $contain_1 = ["userid" => $to_user, "touserid" => $user_id, "type" => -1, 'single' => 1, "content" => $matchContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                            $contain_2 = ["userid" => $user_id, "touserid" => $to_user, "type" => 0, "content" => $content, 'finish' => 1];

                            Db::name('privatechat')->insert($contain_1);
                            Db::name('privatechat')->insert($contain_2);
                        } else if ($fate) {
                            $contain = ["userid" => $user_id, "touserid" => $to_user, "content" => $content, 'finish' => 1];

                            Db::name('privatechat')->insert($contain);
                            // 更新会话列表
                            //D('ChatLists')->updateLists($userid, $touserid, 0, 0, $content);
                        } else if ($login_greet) {
                            $contain = ["userid" => $user_id, "touserid" => $to_user, 'single' => 1, "content" => $content, 'finish' => 1];

                            Db::name('privatechat')->insert($contain);
                        } else if ($notice) {
                            $contain = ["userid" => $user_id, "touserid" => $to_user, 'single' => $single, "content" => $content, 'finish' => 1];

                            Db::name('privatechat')->insert($contain);
                            // 更新会话列表
                            //D('ChatLists')->updateLists($userid, $touserid, $single, 0, $content);
                        } else {
                            if ($userInfo['sex'] == '男') {
                                $content = '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~';
                                $greetContent = '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励';
                                $contain_1 = ["userid" => $user_id, "touserid" => $to_user, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE)];
                                $contain_2 = ["userid" => $user_id, "touserid" => $to_user, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                            } else {
                                $greetContent = '❤ ← 丘比特 → 发现你俩今天很有缘~ <br>👄 赶紧聊聊吧，别错过缘分~';
                                $contain_1 = ["userid" => $user_id, "touserid" => $to_user, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                $contain_2 = ["userid" => $user_id, "touserid" => $to_user, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'finish' => 1];
                            }

                            Db::name('privatechat')->insert($contain_1);
                            Db::name('privatechat')->insert($contain_2);
                        }
                    }
                }

                if ($user_id != $kefu && !$greet && !$notice) {
                    // 日常任务
                    /*$task = M('task')->where(['name' => 'word_chat'])->find();
                    if (($task['reward'] + 0) && ($task['max'] + 0)) {
                        $start = strtotime(date('Ymd'));
                        //$cost = M('volley_desc')->where(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'time' => ['egt', $start]])->sum('price');

                        $cost = M('task_daily')->where(['user_id' => $userid, 'name' => $task['name'], 'create_time' => ['egt', $start]])->sum('reward');

                        if (($cost + $task['reward']) <= $task['max']) {
                            D('Task')->updateTaskDaily($userid, $task['name'], $task['reward']);

                            M('user_task')->add(['task' => $task['name'], 'user_id' => $userid, 'create_time' => time()]);

                            M('volley_desc')->add(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'price' => $task['reward'], 'types' => 1, 'time' => time()]);

                            M('user')->where(['id' => $userid])->setInc('volley', $task['reward']);
                        }
                    }*/

                    // 任务
                    Task::finish('word_chat', $user_id);
                }
                $msg = $content;
                break;
            case 1:
                if (!$content) return $this->miss('内容不能为空');

                if ($kefu == $user_id || $kefu == $to_user) {
                    $chat_free = 1;
                }

                if (!$chat_free) {
                    if ($status) {
                        $money = $touserConfig['chat_price'];

                        if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                            $gradeNoble = Db::name('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                            if ($gradeNoble) {
                                $privilege = explode(',', $gradeNoble['privilege']);

                                if (in_array(10, $privilege)) {
                                    $privilegeValue = explode(',', $gradeNoble['value']);

                                    if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                        $userCount = Db::name('grade_noble_use')->where(['types' => 2, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                        $privilegeValue[0] = intval($privilegeValue[0]);
                                        if ($privilegeValue[0] > $userCount) {
                                            Db::name('grade_noble_use')->insert(['types' => 2, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                            //$touserConfig['chat_price'] = 0;

                                            $free = 1;
                                        }
                                    }
                                }
                            }
                        }

                        if (!$free) {
                            if ($recharge_user['free_chat']) {
                                /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                if ($chatCount >= $config['chat_count']) {
                                    exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                } else {
                                    M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                    $money = 0;
                                }*/

                                Db::name('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');
                            } else {
                                if ($recharge_user['volley'] < $money) {
                                    if ($recharge_user['id'] == $user_id) {
                                        return $this->miss('余额不足，无法发送消息', 300);
                                    } else {
                                        return $this->miss('对方余额不足，无法发送消息');
                                    }
                                }
                            }
                        }
                    }

                    $money = $free ? 0 : $money;

                    if ($recharge_user['id'] == $user_id) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }

                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                    }

                    /*if ($recharge_user['id'] == $userid) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                    }*/

                    /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => 0];
                    }*/
                } else {
                    $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'finish' => 1];
                }

                // 添加聊天
                $id = Db::name('privatechat')->insert($contain);

                $msg = '[图片]';

                // 更新会话列表
                //D('ChatLists')->updateLists($userid, $touserid, 0, 1);

                break;
            case 2:
                if (!$content) return $this->miss('内容不能为空');

                if ($kefu == $user_id || $kefu == $to_user) {
                    $chat_free = 1;
                }

                if (!$chat_free) {
                    if ($status) {
                        $money = $touserConfig['chat_price'];

                        $response = Chat::checkFree($free, $money, $recharge_user, $user_id);

                        if ($response['code'] != 200) {
                            exit(json_encode($response));
                        } else {
                            $free = $response['data']['free'];
                        }
                    }

                    $money = $free ? 0 : $money;

                    if ($recharge_user['id'] == $user_id) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }

                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                    }

                    /*if ($recharge_user['id'] == $userid) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                    }*/

                    /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                    }*/

                } else {
                    $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, "second" => $second, 'finish' => 1];
                }

                $id = Db::name('privatechat')->insert($contain);

                $msg = '[语音]';
                break;
            case 3:
                if (!$content) return $this->miss('内容不能为空');

                if ($kefu != $user_id && $kefu != $to_user) { // 非客服咨询
                    // 被动聊天不扣费
                    /*$chatFreeUser = M('chat_free')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                    if ($chatFreeUser) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') {
                            $greetRecords = M('greet_records')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                            if (!$greetRecords) {
                                $chat_free = 1;
                            }
                        } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                            $greetRecords = M('greet_records')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                            if (!$greetRecords) {
                                $chat_free = 1;
                            }
                        } else {
                            $chat_free = 1;
                        }
                    } else {
                        $chatFreeToUser = M('chat_free')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                        if (!$chatFreeToUser) {
                            $record = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserInfo['id'], 'touserid' => $userInfo['id']])->find();

                            if (!$record) {
                                M('chat_free')->add(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id'], 'create_time' => time()]);
                            }
                        }
                    }*/
                } else {
                    $chat_free = 1;
                }

                if (!$chat_free) {
                    if ($status) {
                        $money = $touserConfig['chat_price'];

                        $response = Chat::checkFree($free, $money, $recharge_user, $user_id);

                        if ($response['code'] != 200) {
                            exit(json_encode($response));
                        } else {
                            $free = $response['data']['free'];
                        }
                    }

                    $money = $free ? 0 : $money;

                    if ($recharge_user['id'] == $user_id) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }

                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => 0];
                    }

                    /*if ($recharge_user['id'] == $userid) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                    }*/

                    /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => 0];
                    }*/
                } else {
                    $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'finish' => 1];
                }

                // 添加聊天
                $id = Db::name('privatechat')->insert($contain);

                $msg = '[视频]';

                // 更新会话列表
                //D('ChatLists')->updateLists($userid, $touserid, 0, 3);

                break;
            case 8:
                $gift_id = $this->params['gift_id'] ?? 0;
                $num = $this->params['num'] ?? 1;
                $num = intval($num);

                if (!$gift_id) return $this->miss('礼物不存在');
                if ($num <= 0) return $this->miss('数量有误');

                $gift = Db::name('gift')->find($gift_id);
                if (!$gift) return $this->miss('礼物不存在');

                if ($gift['types'] == 2) {
                    if (!$userInfo['noble_grade'] || $userInfo['noble_time'] < time()) {
                        return $this->miss('需先开通VIP');
                    }

                    $gradeNoble = Db::Query("SELECT * from grade_noble where FIND_IN_SET(6, privilege) order by grade asc limit 1");

                    if (!$gradeNoble) return $this->miss('无权限');

                    if ($userInfo['noble_grade'] < $gradeNoble[0]['grade']) {
                        return $this->miss('需先开通' . $gradeNoble[0]['name'] . 'VIP或以上等级的VIP');
                    }
                }

                $money = $gift['price'] * $num;

                $time = time();
                $number = date('YmdHis') . mt_rand(1000, 9999);

                //$volley = M('user')->where(['id' => $userid])->getField('volley');
                $volley = $userInfo['volley'];
                if ($userInfo['sex'] == '男') {
                    if ($volley < $money * (1 + 0.03)) return $this->miss('余额不足');
                    // 额外金额注释
                    //if ($volley < $money) return $this->miss('余额不足');
                } else {
                    if ($volley < $money) return $this->miss('余额不足');
                }

                // 添加聊天
                $id = Db::name('privatechat')->insert([
                    "userid" => $user_id,
                    "touserid" => $to_user,
                    "type" => $type,
                    "content" => '[礼物]',
                    'money' => $money,
                    'score' => $money * 1,
                    'finish' => 1,
                    "data" => json_encode(['money' => $money, 'id' => $gift_id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name'],'preview'=>$gift['preview'],'videourl'=>$gift['videourl'],'videojson'=>$gift['videojson']]),
                ]);


                /*M('gift_record')->add([
                    'num' => $num,
                    'gift_id' => $gift['id'],
                    'user_id' => $userid,
                    'to_user' => $touserid,
                ]);*/

                if ($money > 0) {
                    // 扣除余额
                    Balance::index($user_id, $money * 1, '给' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);

                    // 创建订单
                    Db::name('order_common')->insert([
                        'number' => $number,
                        'user_id' => $user_id,
                        'money' => $money,
                        'status' => 1,
                        'types' => 4,
                        'data' => json_encode(['id' => $id, 'touserid' => $to_user, 'num' => $num]),
                        'create_time' => $time,
                        'update_time' => $time,
                    ]);

                    // 电视墙
                    /*if ($userInfo['speaker'] != 3) {
                        if ($config['speaker_min'] <= $money) {

                            $background = '';
                            if ($config['speaker_special'] <= $money) {
                                $speakerBackground = M('speaker_background')->where(['id' => ['gt', 0]])->order('rand()')->find();

                                if ($speakerBackground) {
                                    $background = $speakerBackground['image'];
                                }
                            }

                            $speakerBlock = M('speaker_block')->where(['min' => ['elt', $money]])->order('min desc')->find();
                            $block = $speakerBlock ? $speakerBlock['second'] : $config['expire'];

                            if ($userInfo['speaker'] == 1) {
                                $user_id = $userid;
                                $user_name = $userInfo['name'];
                            } else {
                                $user_id = '';
                                $user_name = '神秘人';
                            }

                            if ($touserInfo['speaker'] == 1) {
                                $another_id = $touserid;
                                $another_name = $touserInfo['name'];
                            } else {
                                $another_id = '';
                                $another_name = '神秘人';
                            }

                            M('speaker')->add([
                                'types' => 2,
                                'user_id' => $userid,
                                'to_user' => $touserid,
                                'content' => '',
                                'data' => json_encode([
                                    'gift_id' => $id,
                                    'gift_name' => $gift['name'],
                                    'gift_cover' => $gift['cover'],
                                    'gift_price' => $gift['price'],
                                    'gift_num' => $num,
                                    'user_id' => $user_id,
                                    'user_name' => $user_name,
                                    'another_id' => $another_id,
                                    'another_name' => $another_name,
                                    'background' => $background,
                                    'block' => $block,
                                    'time' => date('H:i')
                                ], JSON_UNESCAPED_UNICODE),
                                'create_time' => time(),
                            ]);
                        }
                    }

                    $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . str_replace('home/' . $_SERVER['PATH_INFO'], '', str_replace('apis', '', $_SERVER['SCRIPT_NAME'])) . '/api/Speaker/lists';

                    $data = $this->getcurl($url, []);*/

                    if ($user_id < $to_user) {
                        $field_count = 'count_a';
                        $couple_a = $user_id . ',' . $to_user;
                        $couple_b = $to_user . ',' . $user_id;
                    } else {
                        $field_count = 'count_b';
                        $couple_a = $to_user . ',' . $user_id;
                        $couple_b = $user_id . ',' . $to_user;
                    }

                    $intimate = Db::name('user_intimate')->where(['couple_a' => $couple_a])->find();
                    if ($intimate) {
                        Db::name('user_intimate')->where(['id' => $intimate['id']])->update([
                            $field_count => $intimate[$field_count] + $money,
                            'intimate' => $intimate['intimate'] + $money * 1,
                            'update_time' => time()
                        ]);
                    } else {
                        Db::name('user_intimate')->insert([
                            'couple_a' => $couple_a,
                            'couple_b' => $couple_b,
                            $field_count => $money,
                            'intimate' => $money * 1,
                            'create_time' => time(),
                            'update_time' => time()
                        ]);
                    }

                    Db::name('user')->where(['id' => $to_user])->setInc('charm_value', $money * 1);

                    // 榜单记录
                    /*$records_types = $touserInfo['sex'] == '女' ? '1,2,3,6' : '1,3,4,6';
                    D('RankingRecords')->index($records_types, $userid, $touserid, $money);*/


                    // 分成
                    $fencheng_content = '收获' . $userInfo['name'] . '(' . $userInfo['id'] . ')赠送的礼物：' . $gift['name'] . 'X' . $num;

                    User::fencheng($to_user, $user_id, $money * 1, 'gift', $fencheng_content);

                    /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                    $result = M('user_defend')->where(['user_id' => $userid, 'to_user' => $touserid])->find();

                    $types = $touserInfo['sex'] == '女' ? 2 : 1;
                    $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $touserInfo['charm_value']]])->order('grade desc')->getField('grade');

                    if ($touserInfo['sex'] == '女') {
                        $gift_money = $gradeCharm * $config['female_times'];
                        if ($gift_money < $config['female_min']) {
                            $gift_money = $config['female_min'];
                        }
                    } else {
                        $gift_money = $gradeCharm * $config['male_times'];
                        if ($gift_money < $config['male_min']) {
                            $gift_money = $config['male_min'];
                        }
                    }

                    if (!$touserInfo['angel']) {

                        $hadMoney = $userid < $touserid ? $intimate['count_a'] : $intimate['count_b'];

                        $mustMoney = $gift_money - ($hadMoney - $money);

                        $isAngel = 0;
                        if ($mustMoney <= $money) {
                            $isAngel = 1;
                        } else {
                            $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                            if ($gradeDefend) {
                                $isAngel = 1;
                            }
                        }

                        if ($isAngel) {
                            M('user')->where(['id' => $touserid])->setField('angel', $userid);
                            M('user_defend')->where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->save(['angel' => 0, 'update_time' => time()]);

                            $isAngel = 1;
                            $update_time = time();

                            // 任务
                            D('Task')->finish('defend', $userid);
                        } else {
                            $isAngel = 0;
                            $update_time = $result ? $result['update_time'] : time();
                        }

                        $defend_money = $hadMoney;
                    } else {
                        $angel = M('user_defend')->where(['to_user' => $touserid, 'angel' => 1])->find();

                        if ($result) {
                            $defend_money_new = $result['money'] + $money;
                        } else {
                            $defend_money_new = $money;
                        }

                        if (($angel['money'] < $defend_money_new) && $angel['user_id'] != $userid && $gift_money <= $defend_money_new) {

                            M('user')->where(['id' => $touserid])->setField('angel', $userid);
                            M('user_defend')->where(['user_id' => ['neq', $userid], 'to_user' => $touserid])->save(['angel' => 0, 'update_time' => time()]);

                            $isAngel = 1;
                            $update_time = time();

                            // 任务
                            D('Task')->finish('defend', $userid);
                        } else {
                            $isAngel = 0;
                            $update_time = $angel['update_time'];
                        }

                        //$defend_money = $result['money'];
                        $defend_money = $defend_money_new;
                    }

                    if ($result) {
                        M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                    } else {
                        M('user_defend')->add([
                            'user_id' => $userid,
                            'to_user' => $touserid,
                            'money' => $defend_money,
                            'angel' => $isAngel,
                            'create_time' => time(),
                            'update_time' => time(),
                        ]);
                    }*/
                }

                $msg = '[礼物]';

                // 更新会话列表
                //D('ChatLists')->updateLists($userid, $touserid, 0, 8);

                break;
            case 11:
                if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                $content = intval($content);

                $where = [
                    'id' => ':id',
                    'user_id' => ':user_id',
                    'is_hidden' => ':is_hidden',
                ];
                $bind = [
                    ':id' => $content,
                    ':user_id' => ['in', [0, $user_id]],
                    ':is_hidden' => 0,
                ];
                $sticker = M('chat_sticker')->field('image')->where($where)->bind($bind)->find();
                if (!$sticker) {
                    exit(json_encode(['code' => 400, 'msg' => '表情不存在或已下线']));
                } else {
                    $content = $sticker['image'];
                }

                if ($kefu == $user_id || $kefu == $to_user) {
                    $chat_free = 1;
                }

                if (!$chat_free) {
                    if ($status) {
                        $money = $touserConfig['chat_price'];

                        $response = Chat::checkFree($free, $money, $recharge_user, $user_id);

                        if ($response['code'] != 200) {
                            exit(json_encode($response));
                        } else {
                            $free = $response['data']['free'];
                        }
                    }

                    $money = $free ? 0 : $money;

                    if ($recharge_user['id'] == $user_id) {
                        if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                            $chat_score = $touserConfig['chat_price'];
                        } else {
                            $chat_score = $money;
                        }

                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                    } else {
                        $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                    }
                } else {
                    $contain = ["userid" => $user_id, "touserid" => $to_user, "type" => $type, "content" => $content, 'finish' => 1];
                }

                $id = Db::name('privatechat')->insert($contain);

                $msg = '[表情]';
                break;
            default:
                exit(json_encode(['code' => 400, 'msg' => '操作错误']));
        }

        if (!$system_greet) {
            if (!in_array($kefu, [$user_id, $to_user]) || !$greet) {
                if (!in_array($type, [8, 9, 10, 11])) {
                    if (!$free && ($money + 0)) {
                        if ($recharge_user['id'] == $user_id || !$chat_free) {
                            $recharge_msg = $recharge_user['id'] == $user_id ? '给' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')发消息扣金币' : $userInfo['name'] . '(' . $userInfo['id'] . ')发消息扣金币';
                            // 扣除余额
                            Balance::index($recharge_user['id'], $money, $recharge_msg);
                        }
                    }
                }

                $scoreChat = Db::name('privatechat')->where(['userid' => $to_user, 'touserid' => $user_id, 'score' => ['gt', 0], 'finish' => 0])->select();

                $ids = [];
                $scoreData = [];
                $scoreUpdate = 0;

                $content = '回复' . $touserInfo['name'] . '(' . $touserInfo['id'] . ')的消息获得积分';

                foreach ($scoreChat as $item) {
                    if (!in_array($item['type'], [8, 9, 10, 11])) {
                        $money = $item['score'];
                    } else {
                        $money = 0;
                    }

                    $scoreData[] = [
                        'uid' => $user_id,
                        'touid' => $to_user,
                        'content' => $content,
                        'money' => $money,
                        'type' => 1,
                        'time' => time(),
                    ];

                    $scoreUpdate += $money;
                    $ids[] = $item['id'];
                }

                if ($scoreUpdate) {

                    if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '女') {

                    } else {
                        // 榜单记录
                        //D('RankingRecords')->index(1, $userid, $touserid, $scoreUpdate * 10);

                        // 分成
                        User::fencheng($user_id, $to_user, $scoreUpdate, 'chat', $content);

                        //M('yaoqing_records')->addAll($scoreData);
                        //M('user')->where(['id' => $userid])->setInc('score', $scoreUpdate);
                        Db::name('user')->where(['id' => $user_id])->setInc('charm_value', $scoreUpdate);
                    }

                    Db::name('privatechat')->where(['id' => ['in', $ids]])->setField('finish', 1);

                    if ($user_id < $to_user) {
                        $field_count = 'count_b';
                        $couple_a = $user_id . ',' . $to_user;
                        $couple_b = $to_user . ',' . $user_id;
                    } else {
                        $field_count = 'count_a';
                        $couple_a = $to_user . ',' . $user_id;
                        $couple_b = $user_id . ',' . $to_user;
                    }

                    $intimate = Db::name('user_intimate')->where(['couple_a' => $couple_a])->find();
                    if ($intimate) {
                        Db::name('user_intimate')->where(['id' => $intimate['id']])->update([
                            $field_count => $intimate[$field_count] + $scoreUpdate * 10,
                            'intimate' => $intimate['intimate'] + $scoreUpdate,
                            'update_time' => time()
                        ]);
                    } else {
                        Db::name('user_intimate')->insert([
                            'couple_a' => $couple_a,
                            'couple_b' => $couple_b,
                            $field_count => $scoreUpdate * 10,
                            'intimate' => $scoreUpdate,
                            'create_time' => time(),
                            'update_time' => time()
                        ]);
                    }
                    /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                    $result = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                    if (!$userInfo['angel']) {

                        $types = $userInfo['sex'] == '女' ? 2 : 1;
                        $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $userInfo['charm_value']]])->order('grade desc')->getField('grade');

                        //$gift_money = $userInfo['sex'] == '女' ? $gradeCharm * 100 : $gradeCharm * 20;

                        if ($userInfo['sex'] == '女') {
                            $gift_money = $gradeCharm * $config['female_times'];
                            if ($gift_money < $config['female_min']) {
                                $gift_money = $config['female_min'];
                            }
                        } else {
                            $gift_money = $gradeCharm * $config['male_times'];
                            if ($gift_money < $config['male_min']) {
                                $gift_money = $config['male_min'];
                            }
                        }

                        $hadMoney = $userid > $touserid ? $intimate['count_a'] : $intimate['count_b'];

                        $mustMoney = $gift_money - ($hadMoney - $money);

                        $isAngel = 0;
                        if ($mustMoney <= $money) {
                            $isAngel = 1;
                        } else {
                            $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                            if ($gradeDefend) {
                                $isAngel = 1;
                            }
                        }

                        if ($isAngel) {
                            M('user')->where(['id' => $userid])->setField('angel', $touserid);
                            M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                            $isAngel = 1;
                            $update_time = time();
                        } else {
                            $isAngel = 0;
                            $update_time = $result ? $result['update_time'] : time();
                        }

                        $defend_money = $hadMoney;
                    } else {
                        $angel = M('user_defend')->where(['to_user' => $userid, 'angel' => 1])->find();

                        if (($angel['money'] < $result['money']) && $angel['user_id'] != $touserid) {

                            M('user')->where(['id' => $userid])->setField('angel', $touserid);
                            M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                            $isAngel = 1;
                            $update_time = time();
                        } else {
                            $isAngel = 0;
                            $update_time = $angel['update_time'];
                        }

                        $defend_money = $result['money'];
                    }

                    if ($result) {
                        M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                    } else {
                        M('user_defend')->add([
                            'user_id' => $touserid,
                            'to_user' => $userid,
                            'money' => $defend_money,
                            'angel' => $isAngel,
                            'create_time' => time(),
                            'update_time' => time(),
                        ]);
                    }*/
                }

                //---------------------------

                // 魅力值
                if ($money + 0) {
                    Db::name('user')->where(['id' => $user_id])->setInc('tycoon', $money * 1);
                }
            }
        }

        // 清除聊天缓存
        /*S("getMsgList$user_id&$to_user", null);
        S("getMsgList$to_user&$user_id", null);*/

        if (!$system_greet) {
            // 推送
            //$datas = json_encode(['type' => 2, 'userid' => $userid, 'name' => $userInfo['name']], JSON_UNESCAPED_UNICODE);
            //D('Push')->send(2, $touserid, $userInfo['name'], $msg, $datas);

            $this->getNewMsg(json_encode(['userid' => $to_user, 'touserid' => $user_id]));
            if ($type != 11 || $greet) {
                $this->getNewMsg(json_encode(['userid' => $user_id, 'touserid' => $to_user]));
            }
            $this->getOtherList(json_encode(['userid' => $to_user, 'count' => '', 'type' => '']));
        }

        $this->getOtherList(json_encode(['userid' => $user_id, 'count' => '', 'type' => '']));

        if ($timing) {
            $this->getreadcount(json_encode(['user_id' => $to_user]));
        }
    }


        //获取指定信息
    public function MsgLists()
    {
        $userid = $this->params['userid'] ?? 0;
        $touserid = $this->params['touserid'] ?? 0;
        if (!$userid || !$touserid) {
            return $this->pass([]);
        }
        $id = input('id');

        $cache = false;

        if ($cache === false) {

            $lastTime = date('Y-m-d H:i:s');

            $Model = new Chat;

            $users = User::where(['id' => ['in', [(int)$userid, (int)$touserid]]])->cache(86400)->column('id, name, head_100 head_portrait, sex');
            $whereAnd = "";
            if($id){
                $whereAnd = "and id > $id";
            }
            $sql = <<<sql
            select id, type, userid, content, isRead, is_burn, second, status, state, data, k, score, finish, location  from privatechat
            where
                ((userid = $userid and touserid = $touserid and single <> 1 and status not in (-1,1,4))
                                or (userid = $touserid and touserid = $userid and status not in (-1,2,4))) $whereAnd
            order by id desc
sql;

            $data = Db::query($sql);

            if ($data) {
                $ids = implode(',', array_column($data, 'id'));

                $sql = <<<sql
                select *,TIMESTAMPDIFF(SECOND,addtime,NOW()) AS second,
                    TIMESTAMPDIFF(MINUTE,addtime,NOW()) as minute,
                    TIMESTAMPDIFF(HOUR,addtime,NOW()) as hour,
                    TIMESTAMPDIFF(DAY,addtime,NOW()) as day,
                    TIMESTAMPDIFF(WEEK,addtime,NOW()) as week
                from privatechat where id in ($ids)
sql;
                $result = Db::query($sql);

                $rows = [];
                foreach ($result as $key => $item) {
                    $rows[$item['id']] = $item;
                }

                $updates = [];
                foreach ($data as $key => $item) {

                    if (!$item['isRead'] && $item['userid'] != $userid) {
                        $updates[] = $item['id'];
                    }

                    $data[$key]['name'] = $users[$item['userid']]['name'];
                    $data[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                    $data[$key]['self'] = $item['userid'] == $userid ? 1 : 0;

                    $row = $rows[$item['id']];

                    $addtime = $row['addtime'];

                    $data[$key]['addtime'] = $second = floor(strtotime($lastTime) - strtotime($addtime));
                    $data[$key]['showtime'] = $second > 300;
                    $lastTime = $addtime;
                    $data[$key]['timestamp'] = strtotime($addtime);
                    if ($row['week'] > 1) {
                        $data[$key]['time'] = $row['addtime'];
                    } elseif ($row['week'] == 1) {
                        $data[$key]['time'] = '1周前';
                    } elseif ($row['day'] > 0) {
                        $data[$key]['time'] = $row['day'] . '天前';
                    } elseif ($row['hour'] > 0) {
                        $day = strtotime($row['addtime']) < strtotime(date('Ymd')) ? '昨天' : '';
                        $data[$key]['time'] = $day . " " . date('H:i', strtotime($addtime));
                    } elseif ($row['minute'] > 0) {
                        $data[$key]['time'] = $row['minute'] >= 10 ? date('H:i', strtotime($addtime)) : $row['minute'] . '分钟前';
                    } elseif ($row['second'] > 0) {
                        $data[$key]['time'] = $row['second'] . '秒前';
                    }

                    $data[$key]['type'] = $item['type'] == -2 ? 0 : $item['type'];

                    $datas = json_decode($item['data'], true);
                    if (isset($datas['image'])) {
                        $datas['image'] = changeUrl($datas['image']);
                    }

                    if($item['type'] != 13){
                        $datas['cover'] = $datas['cover'] ?? '';
                    }
                    $data[$key]['data'] = $datas;

                    if (in_array($item['type'], [9, 10])) {
                        if (isset($datas['status']) && $datas['status']) {
                            if (isset($datas['start']) && isset($datas['end'])) {
                                $chat_time = $datas['end'] - $datas['start'];
                                $data[$key]['chat_time'] = changeTimeLen($chat_time);
                            } else {
                                if (isset($datas['second']) && $datas['second']) {
                                    $data[$key]['content'] .= changeTimeLen($datas['second'] * 60);
                                } else {
                                    $data[$key]['content'] .= '00:59';
                                }
                            }
                        } else {
                            $data[$key]['content'] .= ' 未接通';
                        }
                    } else if ($item['type'] == 11) {
                        $data[$key]['content'] = changeUrl($item['content']);
                    }
                }

                $ids = array_column($data, 'id');
                array_multisort($ids,SORT_ASC,$data);



                if ($updates) {
                    $Model->where(['id' => ['in', $updates]])->setField('isRead', 1);

                    if ($data) {
                        if ($userid != 5559516 && $touserid != 5559516 && $users[$userid]['sex'] == '男' && $users[$touserid]['sex'] == '女') {
                            $data_count = count($ids);
                            if ($data_count == 1 || (isset($data[$data_count - 1]['showtime']) && $data[$data_count - 1]['showtime'])) {
                                $contain_tip = ['userid' => $userid, 'touserid' => $touserid, 'type' => -1, 'single' => 1, "content" => '对方查看了你的消息', 'finish' => 1, 'is_public' => 1];
                                Db::name('privatechat')->insert($contain_tip);
                                // 更新会话列表
                                // ChatLists::updateLists($userid, $touserid, 1, -1, '对方查看了你的消息');
                            }
                        }
                    }
                }
            }

            /*if (!$page) {
                S("getMsgList$userid&$touserid",$data,3600);
            }*/
        } else {
            $data = $cache;
        }

        // 更新会话列表
        // ChatLists::changeLists($userid, $touserid);

        return $this->pass($data);
    }

    public function uploadDb(){
        $userid = $this->params['userid'] ?? 0;
        if (!$userid) {
            return $this->miss('');
        }
        if(cache('uploadDb' . $userid)){
            return $this->miss('上传时间限制');
        }
        $file = request()->file('file');
        if(!$file){
            return $this->miss('请选择上传文件');
        }
        $info = $file->validate(['ext'=>'db'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'dbs');
        if($info){
            $path = '/public/uploads/dbs/' . $info->getSaveName();
            $path = str_replace('\\','/',$path);
            $insert = array(
                'user_id'=>$userid,
                'path'=>$path,
                'create_time'=>time()
            );
            $befores = Db::name('chat_db_files')->where(['user_id'=>$userid])->select();
            try {
                $res = Db::name('chat_db_files')->insert($insert);
                foreach ($befores as $key => $value) {
                    $fileinsystempath = ROOT_PATH . $value['path'];
                    if(file_exists($fileinsystempath)){
                        @unlink($fileinsystempath);
                    }
                }
                $before_ids = array_column($befores, 'id');
                Db::name('chat_db_files')->where('id', 'in', $before_ids)->delete();
            } catch (\Exception $e) {
                $fileinsystempath = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'dbs' . DS . $info->getSaveName();
                if(file_exists($fileinsystempath)){
                    @unlink($fileinsystempath);
                }
                $res = false;
            }
            if(!$res){
                return $this->miss('上传失败');
            }
            cache('uploadDb' . $userid, 1, 300);

            return $this->pass($path, 'path');
        }else{
            return $this->miss('上传失败');
        }
    }

    public function dbFileNewest(){
        $userid = $this->params['userid'] ?? 0;
        if (!$userid) {
            return $this->pass('');
        }
        if(cache('dbFileNewest' . $userid)){
            return $this->pass('');
        }
        $last_login_app_version = Db::name('user_repeat_check')->where(['user_id'=>$this->member['id']])->value('last_login_app_version');
        if ($last_login_app_version >= 413) return $this->pass('');
        $data = Db::name('chat_db_files')->where(['user_id'=>$userid])->order(['id'=>'desc'])->select();
        $filepath = '';
        foreach ($data as $key => $value) {
            if($value['path'] && file_exists(ROOT_PATH . $value['path'])){
                $filepath = 'http://' . getenv('APP_URL') . $value['path'];
                break;
            }
        }
        try {
            cache('dbFileNewest' . $userid, $filepath, 600);
        } catch (\Exception $e) {
            
        }
        return $this->pass($filepath, 'path');
    }

    public function deltaskstate(){
        $id = input('id');
        $userid = input('userid');
        Db::name('privatechat_dele_task')->where(['id'=>['in', $id], 'userid'=>$userid])->delete();
        return $this->pass('');
    }

    public function deletetask(){
        $userid = input('userid');
        PrivatechatDeleTask::pushtask($userid);
    }


    // 个人招呼语
    public function greetWords($user_id = 0, $verify = 0)
    {
        // if(!$user_id){
        //     return $this->pass([]);
        // }
        
        $user_id = intval($user_id);
        $channel = $this->params['channel'] ? $this->params['channel'] : 2;
        // if ($channel == 1) {
        //     return $this->pass([]);
        // }
        // Cache::rm('greetword' . $user_id);
        $data = Cache::get('greetword' . $user_id . '&channel' . $channel);

        if(!$data || $verify == 1){
            $data = PrivatechatGreet::where([
                'channel' => $channel,
                'user_id' => $user_id,
                'status' => $verify ? ['in', '0,1'] :1,
            ])->field('id, content, voice_time, status')->order('id desc')->limit(20)->select();
            if ($verify == 0) {
                try {
                    Cache::set('greetword' . $user_id . '&channel' . $channel, json_encode($data), 600);
                } catch (\Exception $e) {
                    
                }
            }
        }else{
            $data = json_decode($data);
        }
        
        
        return $this->pass($data);
    }
    
    // 添加个人招呼语
    public function addGreetWords()
    {
        $content = strip_tags($this->params['content']);
        
        if (isset($this->params['word_id']) && $this->params['word_id']) {
            $record = PrivatechatGreet::get(['id' => $this->params['word_id'], 'user_id' => $this->member['id'], 'status' => 1]);
            if (!$record) return $this->return['chat.error.wordNotExist'];
            $update = ['id' => $this->params['word_id'], 'user_id' => $this->member['id'], 'content' => $content, 'status' => 0, 'update_time' => time()];
            $voice_time = input('voice_time');
            if($voice_time){
                $update['voice_time'] = $voice_time;
            }
            PrivatechatGreet::update($update);
        } else {
            // if ($this->params['channel'] == 1) {
            //     return $this->miss('未开放');
            // }
            PrivatechatGreet::create([
                'user_id' => $this->member['id'],
                'channel' => $this->params['channel'] ?? 2,
                'voice_time' => $this->params['voice_time'] ?? 0,
                'content' => $content,
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
        }
        
        Cache::rm('greetword' . $this->member['id'] . '&channel1');
        Cache::rm('greetword' . $this->member['id'] . '&channel2');
        
        return $this->return['chat.success.wait'];
    }
    
    // 删除个人招呼语
    public function delGreetWords()
    {
        $word = PrivatechatGreet::get(['id' => $this->params['word_id'], 'user_id' => $this->params['user_id']]);
        
        if ($word) {
            PrivatechatGreet::destroy($word['id']);
            
            Cache::rm('greetword' . $this->params['user_id'] . '&channel1');
            Cache::rm('greetword' . $this->params['user_id'] . '&channel2');
        } else {
            return $this->return['chat.error.wordNotExist'];
        }
        
        return $this->return['common.success.delete'];
    }


    public function clearchatlists()
    {
        $user_id = $this->member['id'];
        Db::name('chat_lists')->where(['user_id'=>$user_id, 'user_delete'=>0])->update(['user_delete'=>1, 'user_content'=>'', 'user_unread'=>0, 'user_channel'=>0]);
        Db::name('chat_lists')->where(['another_id'=>$user_id, 'another_delete'=>0])->update(['another_delete'=>1, 'another_content'=>'', 'another_unread'=>0, 'another_channel'=>0]);

        Db::name('privatechat')->where(['userid'=>$user_id, 'status'=>0])->update(['status'=>1]);
        Db::name('privatechat')->where(['userid'=>$user_id, 'status'=>3, 'single'=>0])->update(['single'=>1]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>0])->update(['status'=>2]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>3, 'single'=>0])->update(['status'=>2]);


        $dbfiles = Db::name('chat_db_files')->where(['user_id'=>$user_id])->select();
        foreach ($dbfiles as $key => $value) {
            $fileinsystempath = ROOT_PATH . $value['path'];
            if(file_exists($fileinsystempath)){
                try {
                    @unlink($fileinsystempath);
                } catch (\Exception $e) {
                    
                }
            }
        }
        Db::name('chat_db_files')->where(['user_id'=>$user_id])->delete();


        $request = request();

        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';
        $datas = json_encode(['userid' => $user_id], JSON_UNESCAPED_UNICODE);
        sendcurl($url, $datas, 0);

        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getreadcount';
        $datas = json_encode(['user_id' => $user_id], JSON_UNESCAPED_UNICODE);
        sendcurl($url, $datas, 0);
        

        return $this->return['common.success.delete'];
    }


    public function clearchatlistsnew()
    {
        $user_id = $this->member['id'];

        $out = Db::query("(SELECT couple_a from user_intimate where couple_a like '$user_id,%' and intimate >= 2) union (SELECT couple_a from user_intimate where couple_b like '$user_id,%' and intimate >= 2)");
        $uids = [];
        foreach ($out as $key => $value) {
            $uids = array_merge($uids, explode(',',$value['couple_a']));
        }
        $uids = array_unique($uids);

        // Db::name('chat_lists')->where(['user_id'=>$user_id, 'another_delete'=>1])->delete();
        Db::name('chat_lists')->where(['user_id'=>$user_id, 'user_delete'=>0, 'another_id'=>['not in', $uids]])->update(['user_delete'=>1, 'user_content'=>'', 'user_unread'=>0, 'user_channel'=>0]);
        // Db::name('chat_lists')->where(['another_id'=>$user_id, 'user_delete'=>1])->delete();
        Db::name('chat_lists')->where(['another_id'=>$user_id, 'another_delete'=>0, 'user_id'=>['not in', $uids]])->update(['another_delete'=>1, 'another_content'=>'', 'another_unread'=>0, 'another_channel'=>0]);

        Db::name('privatechat')->where(['userid'=>$user_id, 'status'=>0, 'touserid'=>['not in', $uids]])->update(['status'=>1]);
        // Db::name('privatechat')->where(['userid'=>$user_id, 'status'=>2])->delete();
        Db::name('privatechat')->where(['userid'=>$user_id, 'status'=>3, 'single'=>0, 'touserid'=>['not in', $uids]])->update(['single'=>1]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>0, 'userid'=>['not in', $uids]])->update(['status'=>2]);
        // Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>1])->delete();
        Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>3, 'single'=>0, 'userid'=>['not in', $uids]])->update(['status'=>2]);
        // Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>0, 'single'=>1])->delete();
        // Db::name('privatechat')->where(['touserid'=>$user_id, 'status'=>3, 'single'=>0])->delete();


        $dbfiles = Db::name('chat_db_files')->where(['user_id'=>$user_id])->select();
        foreach ($dbfiles as $key => $value) {
            $fileinsystempath = ROOT_PATH . $value['path'];
            if(file_exists($fileinsystempath)){
                try {
                    @unlink($fileinsystempath);
                } catch (\Exception $e) {
                    
                }
            }
        }
        Db::name('chat_db_files')->where(['user_id'=>$user_id])->delete();


        $request = request();
        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';
        $datas = json_encode(['userid' => $user_id], JSON_UNESCAPED_UNICODE);
        sendcurl($url, $datas, 0);

        return $this->return['common.success.delete'];
    }

    public function clearchatlistbyids($ids = '')
    {
        $user_id = $this->member['id'];
        // $user_id = 20032719;
        $chatlists = Db::name('chat_lists')->where(['id'=>['in',$ids]])->column('id,user_id,another_id,user_content,another_content,user_first,another_first');

        $touserids = [];
        foreach ($chatlists as $key => $value) {
            $chatlistkey = '';
            if ($value['user_id'] == $user_id) {
                $chatlistkey = 'another_';
                $touserid = $value['another_id'];
            } else if ($value['another_id'] == $user_id) {
                $chatlistkey = 'user_';
                $touserid = $value['user_id'];
            } else {
                continue;
            }

            $touserids[] = $touserid;

            if ($value['user_first'] || $value['another_first']) {
                continue;
            }

            if ($this->member['sex'] == '男') {
                $systemhichat = Db::name('privatechat')->where(['type'=>0,'userid'=>$touserid, 'touserid'=>$user_id, 'is_public'=>0, 'front_id'=>'', 'content'=>['<>','我在这儿呢']])->find();
                if ($systemhichat) {
                    $hasReply = Db::name('privatechat')->where(['userid'=>$user_id, 'touserid'=>$touserid, 'single'=>0])->find();
                    if ($hasReply) {
                        continue;
                    }
                    Db::name('chat_lists')->where(['id'=>$value['id']])->update([$chatlistkey.'first'=>1]);
                }
            }
        }

        Db::name('chat_lists')->where(['user_id'=>$user_id, 'another_id'=>['in',$touserids], 'user_delete'=>0])->update(['user_delete'=>1, 'user_content'=>'', 'user_unread'=>0, 'user_channel'=>0]);
        Db::name('chat_lists')->where(['another_id'=>$user_id, 'user_id'=>['in',$touserids], 'another_delete'=>0])->update(['another_delete'=>1, 'another_content'=>'', 'another_unread'=>0, 'another_channel'=>0]);

        Db::name('privatechat')->where(['userid'=>$user_id, 'touserid'=>['in',$touserids], 'status'=>0])->update(['status'=>1]);
        Db::name('privatechat')->where(['userid'=>$user_id, 'touserid'=>['in',$touserids], 'status'=>3, 'single'=>0])->update(['single'=>1]);
        Db::name('privatechat')->where(['userid'=>$user_id, 'touserid'=>['in',$touserids], 'status'=>2, 'single'=>0])->update(['status'=>4]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'userid'=>['in',$touserids], 'status'=>0])->update(['status'=>2]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'userid'=>['in',$touserids], 'status'=>3, 'single'=>0])->update(['status'=>2]);
        Db::name('privatechat')->where(['touserid'=>$user_id, 'userid'=>['in',$touserids], 'status'=>1, 'single'=>0])->update(['status'=>4]);

        $request = request();

        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';
        $datas = json_encode(['userid' => $user_id], JSON_UNESCAPED_UNICODE);
        sendcurl($url, $datas, 0);

        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getreadcount';
        $datas = json_encode(['user_id' => $user_id], JSON_UNESCAPED_UNICODE);
        sendcurl($url, $datas, 0);

        return $this->return['common.success.delete'];
    }


    public function aotuinc($data)
    {
        try {
            $d = json_decode($data, true);
            if(!$d || !is_array($d)){
                throw new \Exception("数据错误：", 1);
            }
            $time = time();
            Cache::store('redis')->set('lianmai:' . $d['orderid'], $d['nexttime'] . ' - ' . $time .' = '. ($d['nexttime'] - $time), $d['nexttime'] - $time);
        } catch (\Exception $e) {
            \think\Log::write('连麦持续化监听错误：' . $e->getMessage() . $data, 'error');
        }
    }

    // public function checkMic()
    // {
    //     $orderid = input('orderid');
    //     $version = input('version/d', 1);
    //     $order = Db::name('order_common')->master()->where(['id'=>$orderid])->find();
    //     $chat = Db::name('privatechat')->master()->where(['order_id'=>$orderid])->find();
    //     $timenow = time();
    //     $mineScoketClose = false;
    //     $toScoketClose = false;
    //     if($order && $order['status'] != -1){
    //         $errmsg = '';
    //         try {
    //             $order_data = json_decode($order['data'], true);
    //             if(!is_array($order_data)){
    //                 throw new \Exception("错误的数据", 10004);
    //             }
    //             if(isset($order_data['end'])){
    //                 return $this->miss('通话已断开');
    //             }
    //             if(isset($order_data['start'])){
    //                 $second = 15;
    //                 if ($version == 2) {
    //                     $second = 15;
    //                 }
    //                 // 3秒误差
    //                 if (intval(($timenow - $order_data['start'] + 15) / 60) > $order_data['duration']) {
    //                     throw new \Exception("时间差错误", 10005);
    //                 }
    //             }

    //             if (isset($order_data['start']) && false) {
    //                 $redis = new \Redis();
    //                 $redis->connect('127.0.0.1',6379);
    //                 if(getenv('REDIS_PASS')){
    //                     $redis->auth(getenv('REDIS_PASS'));
    //                 }
    //                 $userorder = $redis->get('zaima:lianmaiuser:'.$order['user_id']);
    //                 $touserorder = $redis->get('zaima:lianmaiuser:'.$order_data['another_id']);

    //                 $userorder_ttl = $redis->ttl('zaima:lianmaiuser:'.$order['user_id']);
    //                 $touserorder_ttl = $redis->ttl('zaima:lianmaiuser:'.$order_data['another_id']);
    //                 if ($this->member['id'] == $order['user_id']) {
    //                     if ($userorder_ttl < 3) {
    //                         $mineScoketClose = true;
    //                     }
    //                     if ($touserorder_ttl < 3) {
    //                         $toScoketClose = true;
    //                     }
    //                 } else {
    //                     if ($userorder_ttl < 3) {
    //                         $toScoketClose = true;
    //                     }
    //                     if ($touserorder_ttl < 3) {
    //                         $mineScoketClose = true;
    //                     }
    //                 }
    //                 $lianmaiuserlast_user_key = 'zaima:lianmaiuserlast:'.$orderid.':'.$order['user_id'];
    //                 $lianmaiuserlast_touser_key = 'zaima:lianmaiuserlast:'.$orderid.':'.$order_data['another_id'];
    //                 $hangupReason = '';
    //                 if (!$userorder) {
    //                     if ($this->member['id'] == $order['user_id']) {
    //                         $mineScoketClose = true;
    //                     } else {
    //                         $toScoketClose = true;
    //                     }
    //                     $socketLastTime = $redis->get($lianmaiuserlast_user_key);
    //                     if ($socketLastTime) {
    //                         $timer = $timenow - $socketLastTime;
    //                         if ($timer >= ($this->member['id'] == $chat['userid'] ? 34 : 39)) {
    //                             $errmsg = $order['user_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
    //                             $hangupReason .= 'uid:'.$order['user_id']."断线";
    //                         }
    //                     } else {
    //                         $errmsg = $order['user_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
    //                         $hangupReason .= 'uid:'.$order['user_id']."断线";
    //                     }
    //                 }
    //                 if (!$touserorder) {
    //                     if ($this->member['id'] == $order_data['another_id']) {
    //                         $mineScoketClose = true;
    //                     } else {
    //                         $toScoketClose = true;
    //                     }
    //                     $socketLastTime = $redis->get($lianmaiuserlast_touser_key);
    //                     if ($socketLastTime) {
    //                         $timer = $timenow - $socketLastTime;
    //                         if ($timer >= ($this->member['id'] == $chat['userid'] ? 34 : 39)) {
    //                             $errmsg = $order_data['another_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
    //                             $hangupReason .= 'uid:'.$order_data['another_id']."断线";
    //                         }
    //                     } else {
    //                         $errmsg = $order_data['another_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
    //                         $hangupReason .= 'uid:'.$order_data['another_id']."断线";
    //                     }
    //                 }
    //                 $yu = ($timenow - $order_data['start']) % 60;
    //                 if ($hangupReason && ($yu >= 54 || $yu == 0)) {
    //                     $redis->del('zaima:lianmai:'.$orderid);
    //                     $chat = Db::name('privatechat')->where(['order_id'=>$orderid])->find();
    //                     if ($chat) {
    //                         $chat_data = json_decode($chat['data'], true);
    //                         if ($chat_data) {
    //                             $chat_data['hpr'] = $hangupReason;
    //                             Db::name('privatechat')->where(['order_id'=>$orderid])->update(['data'=>json_encode($chat_data, JSON_UNESCAPED_UNICODE)]);
    //                         }
    //                         $freeRes = TrtcService::free($chat['userid']);
    //                         // \think\Log::write('TrtcServiceFree '. $freeRes, 'error');
    //                     }
    //                     throw new \Exception($hangupReason, 10005);
    //                 }
    //             }

    //         } catch (\Exception $e) {
    //             \think\Log::write('通话异常 '. $e->getMessage(), 'error');
    //             return $this->miss($errmsg ?: '当前网络较差');
    //         }
    //         if($order['status'] >= 0 && $order['create_time'] + 6 < $timenow && $order_data['types'] == 2){
    //             ShenheTask::CreateTask($chat['userid'],$order['id']);
    //         }
    //         $vailtime = 20;
    //         if ($order_data && isset($order_data['start'])) {
    //             $yu = ($timenow - $order_data['start']) % 60;
    //             if ($yu < 23) {
    //                 $vailtime = 55 - $yu;
    //             } else {
    //                 $vailtime = 55 + 60 - $yu;
    //             }
    //         }
    //         return $this->pass($mineScoketClose?'当前通话你的网络不佳':($toScoketClose?'当前通话对方网络不佳':''), 'msg', ['vailtime'=>$timenow+$vailtime]);
    //     }
    //     return $this->miss('通话已断开');

    // }
    

    public function checkMicold()
{
    
   
    $orderid = input('orderid');
    $version = input('version/d', 1);
    $is_enough = input('is_enough',1);
    $order = Db::name('order_common')->master()->where(['id' =>(int)$orderid])->find();

    // $chat = Db::name('privatechat')->master()->where(['order_id' => $orderid])->find();
    $timenow = time();
    $mineScoketClose = false;
    $toScoketClose = false;
    

    if ($order && $order['status'] != -1) {
        $errmsg = '';
        
        $order_data = json_decode($order['data'], true);
        try {
       
            if (!is_array($order_data)) {
                throw new \Exception("错误的数据", 10004);
            }
            if (isset($order_data['end'])) {
                
                return $this->miss('通话已断开');
            }
            
       
            if (isset($order_data['start'])) {
                $second = 15;
                if ($version == 2) {
                    $second = 15;
                }
                // 3秒误差
                
                // $new_duration =ceil((time()-$order_data['start'])/60) ;
                // $order_data['duration'] =$new_duration;
                // if (intval(($timenow - $order_data['start'] + 15) / 60) > $order_data['duration']) {
                //     throw new \Exception("时间差错误", 10005);
                // }
            }

            if (isset($order_data['start'])) {
                $redis = new \Redis();
                $redis->connect('127.0.0.1', 6379);
                
                if (getenv('REDIS_PASS')) {
                    $redis->auth(getenv('REDIS_PASS'));
                }
                // $userorder = $redis->get('zaima:lianmaiuser:' . $order['user_id']);
                // $touserorder = $redis->get('zaima:lianmaiuser:' . $order_data['another_id']);

                $userorder_ttl = $redis->ttl('zaima:lianmaiuser:' . $order['user_id']);
                $touserorder_ttl = $redis->ttl('zaima:lianmaiuser:' . $order_data['another_id']);
                
                
                

                // 判断是否需要关闭当前连接（客户端）
                if ($this->member['id'] == $order['user_id']) {
                    if ($userorder_ttl <= 5) {
                        $mineScoketClose = true; // 当前用户的连接超时，关闭连接
                    }
                    if ($touserorder_ttl <= 5) {
                        $toScoketClose = true; // 对方用户的连接超时，关闭连接
                    }
                } else {
                    if ($userorder_ttl <= 5) {
                        $toScoketClose = true; // 当前用户的连接超时，关闭连接
                    }
                    if ($touserorder_ttl <= 5) {
                        $mineScoketClose = true; // 对方用户的连接超时，关闭连接
                    }
                }

                // 用户或者对方的连接没有心跳，或者心跳超时
                if ($userorder_ttl === -2 || $touserorder_ttl === -2 || $userorder_ttl < 5 || $touserorder_ttl < 5) {
                    $errmsg = '当前网络较差1';
                }

                // 如果有连接断开
                if ($mineScoketClose || $toScoketClose) {
                    $lianmaiuserlast_user_key = 'zaima:lianmaiuserlast:' . $orderid . ':' . $order['user_id'];
                    $lianmaiuserlast_touser_key = 'zaima:lianmaiuserlast:' . $orderid . ':' . $order_data['another_id'];

                    // 获取上次心跳时间
                    $socketLastTime = $redis->get($lianmaiuserlast_user_key);
                    if ($socketLastTime) {
                        $timer = $timenow - $socketLastTime;
                        if ($timer >= 45) { // 40 秒无心跳，认为掉线
                            $errmsg = $order['user_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
                        }
                    }

                    $socketLastTime = $redis->get($lianmaiuserlast_touser_key);
                    if ($socketLastTime) {
                        $timer = $timenow - $socketLastTime;
                        if ($timer >= 45) { // 40 秒无心跳，认为掉线
                            $errmsg = $order_data['another_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
                        }
                    }
                }

            
  
                // 更新 Redis TTL（续期）
                $result1 = $redis->setex('zaima:lianmaiuser:' . $order['user_id'], 20, 'heartbeat');
                $result2 = $redis->setex('zaima:lianmaiuser:' . $order_data['another_id'], 20, 'heartbeat');
                if(!$result1 || !$result2) $errmsg ='1111';
            }

        } catch (\Exception $e) {
            \think\Log::write('连麦错误信息打印：'.$orderid.date('Y-m-d H:i:s').json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE));
            $money =ceil((time()-$order_data['start'])/60)  * $order_data['price'];
            Db::name('order_common')->where(['id' => $orderid])->update(['money'=>$money]);
                     
                     
            return $this->miss($errmsg ?: '当前网络较差2');
        }

        // 判断订单状态，是否需要创建审核任务等操作
        // if ($order['status'] >= 0 && $order['create_time'] + 6 < $timenow && $order_data['types'] == 2) {
        //     ShenheTask::CreateTask($chat['userid'], $order['id']);
        // }

        $vailtime = 20;
        if ($order_data && isset($order_data['start'])) {
            $yu = ($timenow - $order_data['start']) % 60;
            if ($yu < 23) {
                $vailtime = 55 - $yu;
            } else {
                $vailtime = 55 + 60 - $yu;
            }
        }

        return $this->pass($mineScoketClose ? '当前通话你的网络不佳' : ($toScoketClose ? '当前通话对方网络不佳' : ''), 'msg', ['vailtime' => $timenow + $vailtime,'is_enough'=>$is_enough,'prompt'=>'余额不足,请先充值！！']);
    }

    return $this->miss('通话已断开');
}

  public function checkMic()
{
    $orderid = input('orderid');
    $version = input('version/d', 1);
    $is_enough = input('is_enough',1);
    $order = Db::name('order_common')->master()->where(['id' =>(int)$orderid])->find();
    // $chat = Db::name('privatechat')->master()->where(['order_id' => $orderid])->find();
    $timenow = time();
    $mineScoketClose = false;
    $toScoketClose = false;

    if ($order && $order['status'] != -1) {
        $errmsg = '';
        try {
       
            $order_data = json_decode($order['data'], true);
            if (!is_array($order_data)) {
                throw new \Exception("错误的数据", 10004);
            }
            if (isset($order_data['end'])) {
                return $this->miss('通话已断开');
            }
            if (isset($order_data['start'])) {
                $second = 15;
                if ($version == 2) {
                    $second = 15;
                }
                // 3秒误差
                // if (intval(($timenow - $order_data['start'] + 15) / 60) > $order_data['duration']) {
                //     throw new \Exception("时间差错误", 10005);
                // }
            }

            if (isset($order_data['start'])) {
                $redis = new \Redis();
                $redis->connect('127.0.0.1', 6379);
                if (getenv('REDIS_PASS')) {
                    $redis->auth(getenv('REDIS_PASS'));
                }
                // $userorder = $redis->get('zaima:lianmaiuser:' . $order['user_id']);
                // $touserorder = $redis->get('zaima:lianmaiuser:' . $order_data['another_id']);

                $userorder_ttl = $redis->ttl('zaima:lianmaiuser:' . $order['user_id']);
                $touserorder_ttl = $redis->ttl('zaima:lianmaiuser:' . $order_data['another_id']);

                // 判断是否需要关闭当前连接（客户端）
                if ($this->member['id'] == $order['user_id']) {
                    if ($userorder_ttl <= 5) {
                        $mineScoketClose = true; // 当前用户的连接超时，关闭连接
                    }
                    if ($touserorder_ttl <= 5) {
                        $toScoketClose = true; // 对方用户的连接超时，关闭连接
                    }
                } else {
                    if ($userorder_ttl <= 5) {
                        $toScoketClose = true; // 当前用户的连接超时，关闭连接
                    }
                    if ($touserorder_ttl <= 5) {
                        $mineScoketClose = true; // 对方用户的连接超时，关闭连接
                    }
                }

                // 用户或者对方的连接没有心跳，或者心跳超时
                if ($userorder_ttl === -2 || $touserorder_ttl === -2 || $userorder_ttl < 5 || $touserorder_ttl < 5) {
                    $errmsg = '当前网络较差1';
                }

                // 如果有连接断开
                if ($mineScoketClose || $toScoketClose) {
                    $lianmaiuserlast_user_key = 'zaima:lianmaiuserlast:' . $orderid . ':' . $order['user_id'];
                    $lianmaiuserlast_touser_key = 'zaima:lianmaiuserlast:' . $orderid . ':' . $order_data['another_id'];

                    // 获取上次心跳时间
                    $socketLastTime = $redis->get($lianmaiuserlast_user_key);
                    if ($socketLastTime) {
                        $timer = $timenow - $socketLastTime;
                        if ($timer >= 40) { // 40 秒无心跳，认为掉线
                            $errmsg = $order['user_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
                        }
                    }

                    $socketLastTime = $redis->get($lianmaiuserlast_touser_key);
                    if ($socketLastTime) {
                        $timer = $timenow - $socketLastTime;
                        if ($timer >= 40) { // 40 秒无心跳，认为掉线
                            $errmsg = $order_data['another_id'] == $this->member['id'] ? '当前通话你的网络不佳' : '当前通话对方网络不佳';
                        }
                    }
                }

                // 更新 Redis TTL（续期）
                $result1 = $redis->setex('zaima:lianmaiuser:' . $order['user_id'], 20, 'heartbeat');
                $result2 = $redis->setex('zaima:lianmaiuser:' . $order_data['another_id'], 20, 'heartbeat');
                if(!$result1 || !$result2) $errmsg ='1111';
            }

        } catch (\Exception $e) {
            \think\Log::write('连麦错误信息打印：'.$orderid.date('Y-m-d H:i:s').json_encode($e->getMessage(),JSON_UNESCAPED_UNICODE));
                     
            return $this->miss($errmsg ?: '当前网络较差2');
        }

        // 判断订单状态，是否需要创建审核任务等操作
        // if ($order['status'] >= 0 && $order['create_time'] + 6 < $timenow && $order_data['types'] == 2) {
        //     ShenheTask::CreateTask($chat['userid'], $order['id']);
        // }

        $vailtime = 20;
        if ($order_data && isset($order_data['start'])) {
            $yu = ($timenow - $order_data['start']) % 60;
            if ($yu < 23) {
                $vailtime = 55 - $yu;
            } else {
                $vailtime = 55 + 60 - $yu;
            }
        }

        return $this->pass($mineScoketClose ? '当前通话你的网络不佳' : ($toScoketClose ? '当前通话对方网络不佳' : ''), 'msg', ['vailtime' => $timenow + $vailtime,'is_enough'=>$is_enough,'prompt'=>'余额不足,请先充值！！']);
    }

    return $this->miss('通话已断开');
}


    public function chatOnline($nav = 0, $age = 0, $city = '', $avtive = 0, $occupation = '', $func = '')
    {
        if ($this->member['age'] < 18) {
            return $this->miss('暂不向未成年开放该功能');
        }
        if ($this->member['entertainment'] && $this->member['sex'] == '女') {
            return $this->miss('暂不向非娱乐用户开放该功能');
        }

        $entertainment = input('entertainment');
        $entertainment_child = input('entertainment_child/s','');

        $config = Config::index(['in', ['kefu','push']]);
        $type = input('type/d', 1);
        $where = ['b.voice_switch'=>1, 'b.voice_price'=>['gt', 0]];
        $field = <<<sql
                    a.id,a.name,a.head_portrait as avatar, a.occupation, a.real_avatar, a.age, b.video_price as price, a.city,
                    CASE WHEN a.shouyi>=50000 && a.activeval>=200 THEN 1 
                    WHEN a.shouyi<50000 && a.shouyi>=30000 && a.activeval>=200 THEN 2
                    WHEN a.shouyi<30000 && a.shouyi>=15000 && a.activeval>=200 THEN 3
                    WHEN a.shouyi<15000 && a.shouyi>=10000 && a.activeval>=200 THEN 4
                    WHEN a.shouyi<10000 && a.shouyi>=5000 && a.activeval>=200 THEN 5
                    WHEN a.shouyi<5000 &&  a.shouyi>=3000 && a.activeval>=200 THEN 6
                    WHEN a.shouyi<3000 && a.shouyi>=1000 && a.activeval>=100 THEN 7
                    WHEN a.shouyi<1000 && a.shouyi>=100 && a.activeval>=50 THEN 8 ELSE 0 END AS usort
                    sql;
        if($type == 2){
            $where = ['b.video_switch'=>1,  'b.video_price'=>['gt', 0]];
            $field = <<<sql
                    a.id,a.name,a.head_portrait as avatar, a.occupation, a.real_avatar, a.age, b.video_price as price, a.city,
                    CASE WHEN a.shouyi>=50000 && a.activeval>=200 THEN 1 
                    WHEN a.shouyi<50000 && a.shouyi>=30000 && a.activeval>=200 THEN 2
                    WHEN a.shouyi<30000 && a.shouyi>=15000 && a.activeval>=200 THEN 3
                    WHEN a.shouyi<15000 && a.shouyi>=10000 && a.activeval>=200 THEN 4
                    WHEN a.shouyi<10000 && a.shouyi>=5000 && a.activeval>=200 THEN 5
                    WHEN a.shouyi<5000 &&  a.shouyi>=3000 && a.activeval>=200 THEN 6
                    WHEN a.shouyi<3000 && a.shouyi>=1000 && a.activeval>=100 THEN 7
                    WHEN a.shouyi<1000 && a.shouyi>=100 && a.activeval>=50 THEN 8 ELSE 0 END AS usort
            sql;
        }

        if ($entertainment == '0' || ($entertainment && $entertainment != '1')) {
            $where['a.entertainment'] = $entertainment;
        }
        $where['a.reg'] = 1;
        $where['a.is_online'] = 1;
        $where['a.sex'] = '女';
        $where['a.delete_time'] = 0;
        // 附加条件
        if ($func == 'systemPushLianmai') {
            switch ((int)$this->member['porno_lv']) {
                case 0:
                    $where['a.porno_lv'] = ['in', [0,1]];
                    break;
                case 1:
                    $where['a.porno_lv'] = ['in', [0,1,2]];
                    break;
                case 2:
                    $where['a.porno_lv'] = ['in', [1,2]];
                    break;
                
                default:
                    $where['a.porno_lv'] = ['>', 1];
                    break;
            }
            $where['a.quality'] = ['>=', 3];
            $where['b.system_video_push_reject'] = 0;

            // 用户版本需达到要求
            $spl_app_version_lower = $config['spl_app_version_lower'];
            $where['c.last_login_app_version'] = ['>=', $spl_app_version_lower];
        }
        $agemin = '';
        $agemax = '';
        if (stripos($age, ',')) {
            $age = explode(',', $age);
            $agemin = $age[0];
            $agemax = $age[1];
        } else {
            $agemin = $age ?: $this->member['age'];
        }
        if ($agemin < 18) $agemin = 18;
        if ($agemax) {
            if ($agemax < $agemin) return $this->miss('年龄选择错误');
            $where['a.age'] = ['between', [$agemin, $agemax]];
        } else if ($agemin > 18) {
            $where['a.age'] = ['between', [$agemin - 15 >= 18 ? $agemin - 15 : 18, $agemin]];
        } else {
            $where['a.age'] = 18;
        }
        if ($nav == 1) {
            if (!$age) {
                $where['a.age'] = ['>', 18];
            }
            if (!$func) {
                $where['a.register_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-3 month'))];
            }
        } else if ($nav == 2) {
            if(strpos($this->member['city'],'市') !== false) {
                $this->member['city'] = substr($this->member['city'],0,strrpos($this->member['city'],'市'));
            }
            $where['a.city'] = ['like', $this->member['city'] . '%'];
        }

        if ($city) {
            $where['a.city'] = ['like', $city . '%'];
        }

        if ($occupation) {
            $where['a.occupation'] = $occupation;
        }

        if ($avtive) {
            if ($avtive == 1) {
                $where['a.is_online'] = 1;
            } else if ($avtive == 2) {
                $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-72 hour'))];
            } else if ($avtive == 3) {
                $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-168 hour'))];
            }
        // } else {
        //     $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-30 minute'))];
        }

        $blacklist = Blacklist::lists($this->member['id'], false, true);
        if ($blacklist) {
            $blacklist[] = $config['id'];
        } else {
            $blacklist = [$config['id']];
        }

        if ($entertainment_child) {
            $uids = Db::name('user_entertainment_checked')->where(['entertainment_map'=>['in', $entertainment_child]])->column('user_id');
            $inusers = implode(',', array_diff($uids, $blacklist));
            $where['a.id'] = ['in', $inusers];
        } else {
            $where['a.id'] = ['not in', $blacklist];
        }

        $chatOnlineSkip = Cache::get($this->member['id'] . 'chatOnlineSkip:' . $type . 'n' . $nav);
        if(!$chatOnlineSkip){
            $chatOnlineSkip = rand(0,30);
            Cache::set($this->member['id'] . 'chatOnlineSkip:' . $type . 'n' . $nav, $chatOnlineSkip, 60);
        }
        $page = input('page', 1);
        $pagesize = input('pagesize', 20);
        if ($func == 'systemPushLianmai') {
            $chatOnlineSkip = 0;
            $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-30 minute'))];

            $todayPushs_a = Db::name('push_lianmai_system')->where(['type'=>1])->whereTime('time','-8 hours')->column('user_id');
            $todayPushs_b = Db::name('push_lianmai_system')->where(['type'=>1])->whereTime('time','-8 hours')->column('touserid');
            $unPushs = array_merge($todayPushs_a, $todayPushs_b, $blacklist);
            $where['a.id'] = ['not in', $unPushs];
            $list = Db::name('user')
                    ->alias('a')
                    ->join('config_personal b', 'a.id=b.user_id')
                    ->join('user_repeat_check c', 'a.id=c.user_id')
                    ->where($where)
                    ->limit(($page - 1) * $pagesize + $chatOnlineSkip, $pagesize)
                    ->field($field)
                    // ->fetchSql(true)
                    ->order('a.last_login_datetime desc, usort desc, a.quality desc, a.activeval desc')
                    ->select();
                    // exit($list);
        } else {
            $count = Db::name('user')
                    ->alias('a')
                    ->join('config_personal b', 'a.id=b.user_id')
                    ->where($where)
                    ->limit(100)
                    ->cache(true)
                    ->count();
            if ($count < 100 && $chatOnlineSkip > 0) {
                $chatOnlineSkip = 0;
                Cache::set($this->member['id'] . 'chatOnlineSkip:' . $type . 'n' . $nav, $chatOnlineSkip, 60);
            }
            $list = Db::name('user')
                    ->alias('a')
                    ->join('config_personal b', 'a.id=b.user_id')
                    ->where($where)
                    ->limit(($page - 1) * $pagesize + $chatOnlineSkip, $pagesize * 2)
                    ->field($field)
                    // ->fetchSql(true)
                    // ->order(Db::raw('a.is_online desc, rand()'))
                    ->order('a.last_login_datetime desc, usort desc, a.quality desc, a.activeval desc')
                    ->select();
                    // exit($list);
        }
        $data = [];
        foreach ($list as $key => $value) {
            unset($value['usort']);
            if(sizeof($data) == $pagesize){
                break;
            }
            if(!Cache::store('redis')->get('lianmaiuser:' . $value['id'])){
                $data[] = $value;
            }
        }
        return $this->pass($data);
    }


    public function chatOnlineMale($nav = 0, $age = 0, $city = '', $avtive = 0, $occupation = '', $func = '')
    {
        if ($this->member['age'] < 18 || $this->member['entertainment']) {
            return $this->miss('暂不向未成年开放该功能');
        }

        $config = Config::index(['in', ['kefu','push']]);
        $type = input('type/d', 1);
        $where = ['b.voice_switch'=>1, 'b.voice_price'=>['gt', 0]];
        $field = <<<sql
                    a.id,a.name,a.head_portrait as avatar, a.occupation, a.real_avatar, a.age, b.video_price as price, a.city,
                    CASE WHEN a.volley>=50 THEN 1 
                    WHEN a.volley<200 && a.volley>=100 THEN 2 
                    WHEN a.volley<300 && a.volley>=200 THEN 3 
                    WHEN a.volley>=300 THEN 4 ELSE 0 END AS usort
                    sql;
        if($type == 2){
            $where = ['b.video_switch'=>1,  'b.video_price'=>['gt', 0]];
            $field = <<<sql
                    a.id,a.name,a.head_portrait as avatar, a.occupation, a.real_avatar, a.age, b.video_price as price, a.city,
                    CASE WHEN a.volley>=50 THEN 1 
                    WHEN a.volley<200 && a.volley>=100 THEN 2 
                    WHEN a.volley<300 && a.volley>=200 THEN 3 
                    WHEN a.volley>=300 THEN 4 ELSE 0 END AS usort
            sql;
        }

        $where['a.reg'] = 1;
        $where['a.is_online'] = 1;
        $where['a.sex'] = '男';
        $where['a.delete_time'] = 0;
        $where['a.entertainment'] = 0;
        // 附加条件
        if ($func == 'systemPushLianmai') {
            switch ((int)$this->member['porno_lv']) {
                case 0:
                    $where['a.porno_lv'] = ['in', [0,1]];
                    break;
                case 1:
                    $where['a.porno_lv'] = ['in', [0,1,2]];
                    break;
                case 2:
                    $where['a.porno_lv'] = ['in', [1,2]];
                    break;
                
                default:
                    $where['a.porno_lv'] = ['>', 1];
                    break;
            }
            $where['a.volley'] = ['>=', 40];
            $where['b.system_video_push_reject'] = 0;
        }
        $agemin = '';
        $agemax = '';
        if (stripos($age, ',')) {
            $age = explode(',', $age);
            $agemin = $age[0];
            $agemax = $age[1];
        } else {
            $agemin = $age ?: $this->member['age'];
        }
        if ($agemin < 18) $agemin = 18;
        if ($agemax) {
            if ($agemax < $agemin) return $this->miss('年龄选择错误');
            $where['a.age'] = ['between', [$agemin, $agemax]];
        } else if ($agemin > 18) {
            $where['a.age'] = ['between', [$agemin, $agemin + 15]];
        } else {
            $where['a.age'] = 18;
        }
        if ($nav == 1) {
            if (!$age) {
                unset($where['a.age']);
            }
            if (!$func) {
                $where['a.register_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-3 month'))];
            }
        } else if ($nav == 2) {
            if(strpos($this->member['city'],'市') !== false) {
                $this->member['city'] = substr($this->member['city'],0,strrpos($this->member['city'],'市'));
            }
            $where['a.city'] = ['like', $this->member['city'] . '%'];
        }

        if ($city) {
            $where['a.city'] = ['like', $city . '%'];
        }

        if ($occupation) {
            $where['a.occupation'] = $occupation;
        }

        if ($avtive) {
            if ($avtive == 1) {
                $where['a.is_online'] = 1;
            } else if ($avtive == 2) {
                $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-72 hour'))];
            } else if ($avtive == 3) {
                $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-168 hour'))];
            }
        }

        $blacklist = Blacklist::lists($this->member['id'], false, true);
        if ($blacklist) {
            $blacklist[] = $config['id'];
        } else {
            $blacklist = [$config['id']];
        }
        $where['a.id'] = ['not in', $blacklist];


        $chatOnlineSkip = Cache::get($this->member['id'] . 'chatOnlineSkip:' . $type . 'n' . $nav);
        if(!$chatOnlineSkip){
            $chatOnlineSkip = rand(0,30);
            Cache::set($this->member['id'] . 'chatOnlineSkip:' . $type . 'n' . $nav, $chatOnlineSkip, 60);
        }
        $page = input('page', 1);
        $pagesize = input('pagesize', 20);
        if ($func == 'systemPushLianmai') {
            $chatOnlineSkip = 0;
            $where['a.last_login_datetime'] = ['egt', date('Y-m-d H:i:s', strtotime('-30 minute'))];
            $yesterdayTopupUserids = Db::name('topup')
                                        ->where(['state'=>1])
                                        ->whereTime('addtime','yesterday')
                                        ->column('fk_userid');

            $todayPushs_a = Db::name('push_lianmai_system')->where(['user_id'=>['in', $yesterdayTopupUserids], 'type'=>1])->whereTime('time','today')->column('user_id');
            $todayPushs_b = Db::name('push_lianmai_system')->where(['touserid'=>['in', $yesterdayTopupUserids], 'type'=>1])->whereTime('time','today')->column('touserid');
            $unPushs = array_merge($todayPushs_a, $todayPushs_b, $blacklist);
            $where['a.id'] = ['in', array_diff($yesterdayTopupUserids, array_intersect($yesterdayTopupUserids, $unPushs))];
            $list = Db::name('user')
                    ->alias('a')
                    ->join('config_personal b', 'a.id=b.user_id')
                    ->join('user_repeat_check c', 'a.id=c.user_id')
                    ->where($where)
                    ->limit(($page - 1) * $pagesize + $chatOnlineSkip, $pagesize)
                    ->field($field)
                    // ->fetchSql(true)
                    ->order('last_login_datetime desc, usort desc')
                    ->select();
                    // exit($list);
        } else {
            $list = Db::name('user')
                    ->alias('a')
                    ->join('config_personal b', 'a.id=b.user_id')
                    ->where($where)
                    ->limit(($page - 1) * $pagesize + $chatOnlineSkip, $pagesize)
                    ->field($field)
                    // ->fetchSql(true)
                    ->order('last_login_datetime desc, usort desc')
                    ->select();
                    // exit($list);
        }
        $data = [];
        foreach ($list as $key => $value) {
            unset($value['usort']);
            if(sizeof($data) == 10){
                break;
            }
            if(!Cache::store('redis')->get('lianmaiuser:' . $value['id'])){
                $data[] = $value;
            }
        }
        return $this->pass($data);
    }



    public function rmmsg()
    {
        $ids = input('ids');
        if(!$ids){
            return $this->miss('');
        }
        $ids = explode(',', $ids);
        $user_id = input('user_id');
        $msgs = Db::name('privatechat')->where(['userid|touserid'=>$user_id, 'id'=>['in', $ids], 'type'=>['in','1,2,3,4']])->select();
        $senddels = [];
        $recedels = [];
        $alldels = [];
        $delfiles = [];
        $touserids = [];
        foreach ($msgs as $key => $value) {
            if($value['status'] == 1){
                if($value['touserid'] == $user_id){
                    $alldels[] = $value['id'];
                    $delfiles[] = $value['content'];
                    $touserids[] = $value['userid'];
                }
            }elseif($value['status'] == 2){
                if($value['userid'] == $user_id){
                    $alldels[] = $value['id'];
                    $delfiles[] = $value['content'];
                    $touserids[] = $value['touserid'];
                }
            }elseif($value['status'] == 3){
            }else{
                if($value['userid'] == $user_id){
                    $senddels[] = $value['id'];
                    $touserids[] = $value['touserid'];
                }else{
                    $recedels[] = $value['id'];
                    $touserids[] = $value['userid'];
                }
            }
        }
        $res = false;
        if(sizeof($senddels)){
            $res = Db::name('privatechat')->where(['id'=>['in', $senddels]])->update(['status'=>1]);
        }
        if(sizeof($recedels)){
            $res = Db::name('privatechat')->where(['id'=>['in', $recedels]])->update(['status'=>2]);
        }
        if(sizeof($alldels)){
            $res = Db::name('privatechat')->where(['id'=>['in', $alldels]])->update(['status'=>4]);
            if(sizeof($delfiles)){
                foreach ($delfiles as $key => $value) {
                    AliOss::delete($value, false);
                }
            }
        }
        if($res){
            $touserids = array_unique($touserids);
            $ChatLists = new ChatLists;
            foreach ($touserids as $key => $value) {
                $ChatLists->changeLists($user_id, $value, 'delete_one');
            }
            return $this->pass('清理成功');
        }else{
            return $this->miss('清理失败');
        }
    }


    public function msgstate()
    {
        $user_id = input('user_id');
        $touserid = input('touserid');
        $ids = input('ids');
        $msgs = Db::name('privatechat')->where(['userid|touserid'=>$user_id, 'userid|touserid'=>$touserid, 'id'=>['in', $ids]])->field('id,type,state')->select();
        return $this->pass($msgs);
    }

    public function changeChatPayer($touserid)
    {
        $user_privacy = $user = $this->member;
        $touserid_privacy = $touserid;
        if ($this->member['reg'] == 2) {
            $user = Db::name('user')->where(['id'=>$this->member['authcode']])->find();
            $touserid = Db::name('user')->where(['id'=>$touserid])->value('authcode');
        }
        $ChatChargeRecordsMap = $user['id'] < $touserid ? [
            'user_id' => $user['id'],
            'another_id' => $touserid,
        ] :  [
            'user_id' => $touserid,
            'another_id' => $user['id'],
        ];
        $ChatChargeRecords = Db::name('chat_charge_records')->master(true)->where($ChatChargeRecordsMap)->find();
        if ($ChatChargeRecords && $ChatChargeRecords['payer']) {
            if ($ChatChargeRecords['payer'] == $user['id']) {
                $res = Db::name('chat_charge_records')->where(['id' => $ChatChargeRecords['id']])->update(['payer' => $touserid, 'state' => 0]);
                if ($res) {
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touserid_privacy]));
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $user_privacy['id']]));
                    return $this->pass('已发起变更');
                }
                return $this->miss('发起变更失败');
            }
            return $this->miss('仅当前付费者可发起修改');
        }
        return $this->miss('还未开始聊天无法变更');
    }

    public function all_read()
    {
        $touser1 = db('chat_lists')->where(['user_id'=>$this->member['id'], 'user_unread'=>['>', 0]])->column('another_id');
        $touser2 = db('chat_lists')->where(['another_id'=>$this->member['id'], 'another_unread'=>['>', 0]])->column('user_id');
        $touserids = array_merge($touser1, $touser2);
        foreach ($touserids as $key => $value) {
            (new \app\service\TencentIM)->admin_set_msg_read($this->member['id'], $value);
        }

        db('privatechat')->where(['touserid'=>$this->member['id'], 'isRead'=>0])->update(['isRead'=>1]);
        db('chat_lists')->where(['user_id'=>$this->member['id']])->update(['user_unread'=>0]);
        db('chat_lists')->where(['another_id'=>$this->member['id']])->update(['another_unread'=>0]);

        return $this->pass('操作成功');
    }

}
